Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do commas behave differently in int.Parse() and decimal.Parse() with InvariantCulture?

Why does:

decimal.Parse("1,2,3,45", CultureInfo.InvariantCulture)

return a decimal of 12345, yet:

int.Parse("1,2,3,45", CultureInfo.InvariantCulture)

throws an exception? I would expect the commas to be treated the same for the same culture. If decimal.Parse returns 12345, why doesn't int.Parse also return 12345?

like image 432
Danny Tuppeny Avatar asked Nov 29 '11 13:11

Danny Tuppeny


People also ask

What does CultureInfo Invariantculture mean?

The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a CultureInfo instantiation method. CultureInfo.

Why do we use int parse?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str);


1 Answers

See NumberStyles

The default NumberStyles for int is Integer:

Integer Indicates that the AllowLeadingWhite, AllowTrailingWhite, and AllowLeadingSign styles are used. This is a composite number style.

Compare to Number (used for decimal):

Number Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style.

If you want more, use the overload that accepts NumberStyles, and supply (for example) NumberStyles.Number or NumberStyles.Any:

int i = int.Parse("1,2,3,45", NumberStyles.Number, CultureInfo.InvariantCulture);
like image 168
Marc Gravell Avatar answered Oct 14 '22 18:10

Marc Gravell