In C#, why can't int.TryParse parse number grouping (but double.TryParse can)?
int i1 = 13579;
string si1 = i1.ToString("N0"); //becomes 13,579
int i2 = 0;
bool result1 = int.TryParse(si1, out i2); //gets false and 0
double d1 = 24680.0;
string sd1 = d1.ToString("N0"); //becomes 24,680
double d2 = 0;
bool result2 = double.TryParse(sd1, out d2); //gets true and 24680.0
???
You have to specify the allowed NumberStyles
, which is taken into account when parsing the string back into a number.
Determines the styles permitted in numeric string arguments that are passed to the Parse and TryParse methods of the integral and floating-point numeric types.
This returns true
and stores the expected number in i2
:
bool result1 = int.TryParse(si1,
NumberStyles.AllowThousands, CultureInfo.CurrentCulture.NumberFormat, out i2);
You may also want to take a look at the other NumberStyles
options. For example, NumberStyles.Number
allows thousands as well as decimal points, white space, etc.
The default value for int.TryParse
(if none is specified) is NumberStyles.Integer
, which allows only a leading sign, and leading and trailing white space.
The default for double.TryParse
is NumberStyles.Float| NumberStyles.AllowThousands
, which allows leading sign and white space, but also thousands, exponents and decimal points.
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