Frage

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

???

War es hilfreich?

Lösung 2

Because the conversion factor of both data type is different. parameter assigned in string value will be different from both data type.

in Int.TryParse does not contains culture specific thousand separator parameter in form of conversion parameter

for example

in Int.TryParse the form of parameter is

[ws][sign]digits[ws]

ws: White space (optional)
sign: An optional Sign (+-)
digit: sequance of digit (0-9)

and in Decimal.TryParse the form of parameter is

[ws][sign][digits,]digits[.fractional-digits][ws]

ws: White space (optional)
sign: An optional Sign (+-)
digit: sequance of digit (0-9)
,: culture specific thousand separator
.: culture specific decimal point.
fractional-digits: fractional digit after decimal point.

You can get more information from msdn. Int.TryParse and Decimal.TryParse

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top