Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToInt32 behavior string vs float/double literal

Convert.ToInt32 behaves different when passed string vs float/double literal

var result = Convert.ToInt32(12.4);//returns 12
result = Convert.ToInt32(12.44);//returns 12
result = Convert.ToInt32(12.4444444);//returns 12       
result = Convert.ToInt32("12.4"); // Input string was not in a correct format.

I understand different overloads of Convert.ToInt32 are being called for string and float/double

The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?

like image 296
Ankit Avatar asked Feb 10 '26 15:02

Ankit


1 Answers

The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?

You can think of the utility methods you're currently using to convert from double to int as "casting" i.e (int)12.4, (int)12.44 etc. which in essence means you for sure know that there is high chance that you'll lose data precision, thus in short is like telling the compiler "go ahead and convert it as I don't mind data loss", so, no exception will be thrown whereas the last example that converts from string to int should throw an exception because according to MSDN:

ToInt32(String) method is equivalent to passing value to the Int32.Parse(String).

and as we all know Int32.Parse(String) throws an exception if the specified string is not in the correct format.

like image 66
Ousmane D. Avatar answered Feb 13 '26 05:02

Ousmane D.



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!