Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# thousand separator issue with decimal.tryparse

Tags:

c#

I am not sure how this is able to be parsed correctly in C# but I would like it to fail where the case where the comma is not separated every repeatable three value. Example: 1,123.23 should pass but 11,23.23 should fail in my sense. But the actual output is that tryparse seems to always return true regardless of where the position of comma is before decimal.

Edit: Answer with regex is being accepted since it is found that this is a bug. Thank you.

 string price = "1,1,2,3.23";
 decimal outputValue = 0;
 var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);


 if (Decimal.TryParse(price, allowedStyles, CultureInfo.GetCultureInfo("EN-us"), out outputValue))
 {
    Console.WriteLine("Pass");
 }
like image 577
stackdisplay Avatar asked Nov 28 '15 13:11

stackdisplay


1 Answers

As you noted NumberStyles.AllowThousands doesn't enforce the comma to be on the correct place. So I think a regular expression can help you here:

Regex.IsMatch("11,23.23", "^[+-]?[0-9]{1,3}(,[0-9]{3})*(.[0-9]*)?$");
like image 69
huysentruitw Avatar answered Sep 28 '22 05:09

huysentruitw