Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decimal.TryParse successfully parse something like 12,2,2,2

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.

like image 668
Ben Avatar asked Sep 17 '14 20:09

Ben


4 Answers

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

like image 140
SLaks Avatar answered Nov 15 '22 08:11

SLaks


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
like image 26
brz Avatar answered Nov 15 '22 09:11

brz


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.

like image 25
David Heffernan Avatar answered Nov 15 '22 09:11

David Heffernan


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

like image 1
Chris Knight Avatar answered Nov 15 '22 08:11

Chris Knight