How do I parse a string with a decimal point to a double?

前端 未结 19 1284
孤街浪徒
孤街浪徒 2020-11-22 06:47

I want to parse a string like \"3.5\" to a double. However,

double.Parse(\"3.5\") 

yields 35 and

double.Pars         


        
19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 07:04

    I couldn't write a comment, so I write here:

    double.Parse("3.5", CultureInfo.InvariantCulture) is not a good idea, because in Canada we write 3,5 instead of 3.5 and this function gives us 35 as a result.

    I tested both on my computer:

    double.Parse("3.5", CultureInfo.InvariantCulture) --> 3.5 OK
    double.Parse("3,5", CultureInfo.InvariantCulture) --> 35 not OK
    

    This is a correct way that Pierre-Alain Vigeant mentioned

    public static double GetDouble(string value, double defaultValue)
    {
        double result;
    
        // Try parsing in the current culture
        if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
            // Then try in US english
            !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
            // Then in neutral language
            !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
        {
            result = defaultValue;
        }
        return result;
    }
    

提交回复
热议问题