For the first case, from Microsoft Source Code Reference, by default Int32.Parse
implements NumberStyles.Integer but not NumberStyles.AllowThousands
public static int Parse(String s) {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
Thus any comma separator is not allowed. This:
Int32.Parse("1,234");
or
Int32.Parse("1.234");
will both be wrong. In any culture.
To fix it, NumberStyles.AllowThousands
must be added to the NumberStyles
which will allow "1,234" to be parsed in EN-US
culture:
Int32.Parse("1,234", NumberStyles.Integer | NumberStyles.AllowThousands);
But
Int32.Parse("1.234", NumberStyles.Integer | NumberStyles.AllowThousands);
Will still throw
an Exception
.
For the second case, according to Microsoft Code Source Reference, the default style for Single.Parse
is:
public static float Parse(String s) {
return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
Which allows thousands separator. And ","
is recognized as thousand separator in EN-US
culture, for Single.Parse
and thus you get the second case parsed correctly
Single.Parse("1,234"); //OK
And obviously "1.234" will also be correct, except that "." is not recognized as thousand separators but decimal separator.
As for the third case, Internally, Single.Parse
calls TryStringToNumber
, and Parse.Number which would simply ignore the thousand separators. Thus you get:
Single.Parse("1,2,3,4"); //Returns 1234
Because it is equivalent as
Single.Parse("1234"); //Returns 1234