Search code examples
c#numbersformatlocale

Why can't int.TryParse parse number grouping (but double.TryParse can)?


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

???


Solution

  • 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