If I do the following:
string teststring = "12,2,2,2";
decimal testdecimal;
decimal.TryParse(teststring, out testdecimal)
This works and testdecimal ends up being 12222.
Shouldn't this reasonably/logically fail parsing? I was surprised to see that it worked and was curious as to what is the logic behind it that allows this.
By default, TryParse()
allows group separators, which are ,
in your country.
To prevent this, pass a NumberStyles
that does not include NumberStyles.AllowThousands
.
The default is:
Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowDecimalPoint | AllowThousands,
Source
It's because of digit group separators. When dealing with money types it's common to use a thousand separator. Decimal.TryParse considers the commas as thousand separator and parses it anyway. However, you have to note that this method is culture sensitive. For example if current culture is set to Turkish, TryParse won't be successful because in Turkish ,
is decimal point not thousand separator.
var d1 = Decimal.Parse("1,23,25"); //parse is successful
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr");
d1 = Decimal.Parse("1,23,45"); //throws exception
Your culture settings have ,
as the thousands separator. Since the thousands separator is purely for visual cues, and does not provide any significant information about the number, decimal.TryParse
simply ignores thousands separators.
It is because of the thousands separator for the Decimal parsing. If you want to disallow the thousands separators, you can just remove that flag, like this:
Decimal.Parse("12,2,2,2", NumberStyles.Number ^ NumberStyles.AllowThousands)
This will throw an InvalidFormatException
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