Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Convert.ToInt32("10.0") fails

Not only in .NET, but such conversion fails even in SQL Server 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")
like image 581
The King Avatar asked Jan 27 '26 02:01

The King


2 Answers

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.

like image 62
Jon Skeet Avatar answered Jan 29 '26 00:01

Jon Skeet


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 ..

like image 33
Darin Dimitrov Avatar answered Jan 28 '26 23:01

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!