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

1

15

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?

Bomb answered 29/11, 2011 at 13:24 Comment(0)
O
23

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);
Obsequent answered 29/11, 2011 at 13:30 Comment(1)
Interesting - I didn't realise they used different styles. I can understand some of them (eg. AllowDecimalPoint), but seems strange that AllowThousands is different between the two. Thanks!Bomb

© 2022 - 2024 — McMap. All rights reserved.