字符串转换问题,字符串是十进制或整数或null或balnk。 [英] string conversion problem , string is either decimal or integer or null or balnk.

查看:78
本文介绍了字符串转换问题,字符串是十进制或整数或null或balnk。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果写入convert.ToInt32()则它不会将转换为0并且它也不会将1.00转换为1.它只将整数格式字符串转换为int32。

如果我使用int.tryparse

它检查字符串是否为然后将0分配给varable但

i错过1.00因为它没有转换到1



任何帮助都是非常感谢谢谢。

if write convert.ToInt32() then it doesnot convert "" to 0 and also it does not convert 1.00 to 1. it only converts only integer format strings to int32.
if i use int.tryparse
it checkes if string is "" then assigns to 0 to varable but
i miss 1.00 as its not converted to 1

any help is appriciated thank you.

推荐答案

是的 - 这是一个整数转换器,所以浮点值无效:它只解析有效的整数字符串!



我首先使用int.TryParse,如果失败,请再次尝试使用double。的TryParse。如果成功,则将值转换为int(假设它适合)并继续。

如果失败,则报告错误或使用默认值。
Well yes - it's an integer converter, so a floating point value is not valid: it only parses valid integer strings!

I would use int.TryParse first, and if that failed, try again with double.TryParse. If that succeeds, then cast the value to an int (assuming it fits) and continue.
If that fails, then report an error or use your default.


尝试 TryParse [ ^ ]适用于不同的类型,例如:

Try TryParse[^] for different types, like this:
using System;

public class Program
{
    public static void Main()
    {
        string[] numberString = {"", "1", "1.00"}

        ;
        int intNumber;
        decimal decimalNumber;
        for (int i = 0; i < numberString.Length; i++)
        {
            if (Int32.TryParse(numberString[i], out intNumber))
            {
                Console.WriteLine(intNumber);
            }
            else if (Decimal.TryParse(numberString[i], out decimalNumber))
            {
                Console.WriteLine(decimalNumber);
            }
            else
            {
                Console.WriteLine("Conversion failed!");
            }
        }
    }
}


这篇关于字符串转换问题,字符串是十进制或整数或null或balnk。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆