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.
For the double conversion, there are two possibilities:
,
is the number group separator. And so the conversion succeeds and returns a value of 1000
.,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With