Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NumberStyles.AllowThousands work for int.Parse but not for double.Parse in this example?

Tags:

c#

To parse a string representing a number, with a comma separating thousand digits from the rest, I tried

int tmp1 = int.Parse("1,234", NumberStyles.AllowThousands);
double tmp2 = double.Parse("1,000.01", NumberStyles.AllowThousands);

The first statement is executed without issues, while the second fails with an exception:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Why do not both succeed?

like image 808
Tim Avatar asked Apr 05 '17 20:04

Tim


People also ask

What does this function do int32 Parse ()?

Converts the string representation of a number to its 32-bit signed integer equivalent.

What is the use of int Parse in C#?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent.

Can you Parse a double C#?

Double Parse(String, NumberStyles, IFormatProvider) converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

What does double Parse mean?

Converts the string representation of a number to its double-precision floating-point number equivalent. Parse(String, NumberStyles) Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.


1 Answers

You should pass AllowDecimalPoint, Float, or Number style (latter two styles are just a combination of several number styles which include AllowDecimalPoint flag):

double.Parse("1,000.01", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint)

When you provide some number style to parsing method, you specify exact style of elements which can present in the string. Styles which are not included considered as not allowed. Default combination of flags (when you don't specify style explicitly) for parsing double value is NumberStyles.Float and NumberStyles.AllowThousands flags.

Consider your first example with parsing integer - you haven't passed AllowLeadingSign flag. Thus the following code will throw an exception:

int.Parse("-1,234", NumberStyles.AllowThousands)

For such numbers, AllowLeadingSign flag should be added:

int.Parse("-1,234", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign)
like image 109
Sergey Berezovskiy Avatar answered Sep 28 '22 02:09

Sergey Berezovskiy