Problem with C # thousand separator. With decimal.tryparse

I am not sure how this can be correctly analyzed in C #, but I would like it to fail, where is the case where the comma is not divided by each repeated three values. Example: 1,123,23 should pass, but 11,23,23 should fail in my sense. But the actual conclusion is that tryparse seems to always return true no matter where the position of the comma is before the decimal point.

Edit: The regex response is accepted because it is detected to be an error. Thanks.

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"); } 
+8
c #
source share
5 answers

As you noted, NumberStyles.AllowThousands does not ensure that the comma is in the right place. So I think regex can help you here:

 Regex.IsMatch("11,23.23", "^[+-]?[0-9]{1,3}(,[0-9]{3})*(.[0-9]*)?$"); 
+3
source share

I executed several different codes, and I realized that when you use AllowThousands, the only restriction in place of "," is that it must be on the integer part of the number.

some results:

  • "123, 3.12" => pass
  • "123, 3.1,3" => fail
+4
source share

I don't know if this helps, but I think I should try. I think that my answer is a bit, but straightforward, only if it is a format, I compared it .ToString ("format specified"); and compare it with the line "price". Only my 2 cents.

 string price = "1,1,2,3.23"; decimal priceParse = 0; if (decimal.TryParse(price, out priceParse)) { string shouldBeFormat = Convert.ToDecimal(priceParse).ToString("#,##0.00"); if (price == shouldBeFormat) { // your good } else { // no good } } 
+3
source share

What you find is clearly a mistake. I highly recommend not getting stuck here, but instead use a workaround. (and also apply KISS).

If this piece of code, executed in milliseconds in a kernel with a high mathematical algorithm or in some other way, is performance critical, here is a simple workaround.

(Suppose strings use ',' (comma) as thousands separator (and they are not decimal separators, as this may be some kind of culture)):

 price = price.Replace(",",""); // This will not change the value when comma is thousand separator. // Go forward to parsing 
+2
source share

You have two acceptable formats, so you can check if the number is processable, and if so, check that it is in an acceptable format:

 string price = "1,123.23"; decimal outputValue = 0; var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands); var cul = CultureInfo.GetCultureInfo("EN-us"); if (decimal.TryParse(price, allowedStyles, cul, out outputValue)) { if (outputValue.ToString("N", cul) == price || outputValue.ToString("G", cul) == price) { Console.WriteLine("Pass"); } } 
+2
source share

All Articles