Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I'm calling the following two lines. The second line crashes.:

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

However, if I modify the values to not have ',' characters and remove the NumberStyles enum it works. e.g.

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

Am I doing something wrong? Is this a known issue? Is there an acceptable work-around that doesn't involve hacky string manipulation?

edit I should have mentioned the exception is a System.FormatException, "Input string was not in a correct format."

like image 345
DaveDev Avatar asked Jun 24 '15 05:06

DaveDev


1 Answers

For your second example, you need to use AllowLeadingSign as well since you using NegativeSign in your string.

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

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

From reference source;

Integer  = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign,
like image 123
Soner Gönül Avatar answered Oct 20 '22 19:10

Soner Gönül