Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string with commas to double and int are different. Why?

I am migrating from an old MFC GUI to C#.

I was building a Form-based GUI when I've got an unexpected exception converting a string to an integer type. I assumed it would work the same as converting string to double.

string str = "1,000";
double dthou = Convert.ToDouble(str);   // OK
int ithou = Convert.ToInt32(str);       // raises an exception

Conversion to double gives correct value: 1000.0. For int conversion, I was able to get a solution : Convert.ToInt32() a string with Commas.

But I am curious if there were any reason behind this. Or, am I missing something?

I was able to find a similar, but not exactly a duplicate question : Number parsing weirdness

[EDIT] after learning about the culture issue.

I am in a kind of a culture-shock because until now, in Korea, both floating point number and integer numbers are expressed with "," for thousands group and "." for decimal point (at least in the real world, in Korea, I mean, I think... ). I guess I will have to accept current settings of MS Visual Studio and carry on.

[EDIT2] after sleeping over this issue.

I think it's more of the inconsistent handling of the formatted string. ToDouble accepts strings with thousands separator (in my culture, comma), but ToInt32 does not. If ToDouble is float | allowThousands, then why could'nt ToInt32 have been integer | allowThousands is what I am asking.

like image 738
Keugyeol Avatar asked Apr 23 '14 11:04

Keugyeol


Video Answer


1 Answers

For the double conversion, there are two possibilities:

  1. In your culture, , is the number group separator. And so the conversion succeeds and returns a value of 1000.
  2. Alternatively, in your culture, , is used as the decimal separator. Again the conversion to floating point succeeds but this time returns 1.

For conversion to integer, "1,000" is simply not an integer. My suspicion, given your naming, is that , is a number group separator for you. And you are expecting it to be treated that way by ToInt32(). But ToInt32() does not accept number group separators. Valid characters for ToInt32() are 0 to 9, the optional sign prefix of - or + and leading or trailing whitespace.

like image 183
David Heffernan Avatar answered Sep 22 '22 02:09

David Heffernan