Why does NumberStyles.AllowThousands throw an exception when passing a negative number?

I call the following two lines. Second line failed:

var a = long.Parse("2,147,483,648", NumberStyles.AllowThousands); var b = long.Parse("-2,147,483,648", NumberStyles.AllowThousands); 

However, if I change the values ​​so that I don't have the "," characters and delete the NumberStyles enumeration, it works. eg.

 var a = long.Parse("2147483648"); var b = long.Parse("-2147483648"); 

Am I doing something wrong? Is this a known issue? Is there an acceptable job that doesn't involve hacker string manipulation?

edit . I should have mentioned the exception: System.FormatException , "The input string was not in the correct format."

+6
source share
1 answer

For your second example, you need to use AllowLeadingSign , since you are using NegativeSign in your line.

 var b = long.Parse("-2,147,483,648", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign); 

When you use long.Parse(string) overload , this method uses the NumberStyles.Integer composite style, which already includes AllowLeadingSign .

From a reference source ;

 Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign, 
+7
source

Source: https://habr.com/ru/post/989652/


All Articles