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?
Converts the string representation of a number to its 32-bit signed integer equivalent.
Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With