开发者

Why Convert.ToInt32("10.0") fails

开发者 https://www.devze.com 2023-02-01 05:44 出处:网络
Not only in .NET, but such conversion fails even in SQL Server开发者_Go百科 2005... Can anyone tell me why ?.

Not only in .NET, but such conversion fails even in SQL Server开发者_Go百科 2005...

Can anyone tell me why ?.

Wouldn't it be prudent to return just the integer part even in case of

    Convert.ToInt32("10.2")


Others have explained why parsing "10.2" as 10 would be a bad idea. Now let's consider "10.0".

"10.0" is a string representation of a number which can have a fractional part - in other words, not an integer.

If you're parsing a value as an integer, you should be parsing an integer representation. "10.0" is almost certainly only coincidentally an integer... the data source isn't obviously a source of integers, so you shouldn't treat them as integers.

If you want the closest integer to a "real" number, you should parse it as a real number, and then round however you want to.

Think of it this way: choosing the right form of parsing is expressing a belief in the format of the input. The current behaviour is telling you that you're guessing badly.


Better fail than return some unexpected result. 10.0 and 10.2 are not integers. If you know that you will be dealing with floating point numbers use the corresponding data type:

float result = Convert.ToSingle("10.2", CultureInfo.InvariantCulture);

Also don't forget to take the culture into account when dealing with floating point numbers as the decimal separator might not always be ..


Because 10.2 is not an integer and it would be better that the programmer would be explicit about the loss of precision.

If this would work and not throw, there is a good chance that unintended loss of precision errors due to incorrect type assignments/conversions would occur.


Convert.ToInt32("10.0") is just call to Int32.Parse("10.0") Which, in its turn equal to Number.ParseInt32("10.0", NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));

Most interesting part here is NumberStyles.Integer value. This is a composite numeber style, including AllowLeadingWhite, AllowTrailingWhite, and AllowLeadingSign styles. Mind that AllowDecimalPoint is not included in NumberStyles.Integer value. So, if string contains decimal point, we have format exception. Because decimal point is not allowed for parsing Int32.

0

精彩评论

暂无评论...
验证码 换一张
取 消