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

前端 未结 19 1296
孤街浪徒
孤街浪徒 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:11

    The following code does the job in any scenario. It's a little bit parsing.

    List inputs = new List()
    {
        "1.234.567,89",
        "1 234 567,89",
        "1 234 567.89",
        "1,234,567.89",
        "123456789",
        "1234567,89",
        "1234567.89",
    };
    string output;
    
    foreach (string input in inputs)
    {
        // Unify string (no spaces, only .)
        output = input.Trim().Replace(" ", "").Replace(",", ".");
    
        // Split it on points
        string[] split = output.Split('.');
    
        if (split.Count() > 1)
        {
            // Take all parts except last
            output = string.Join("", split.Take(split.Count()-1).ToArray());
    
            // Combine token parts with last part
            output = string.Format("{0}.{1}", output, split.Last());
        }
    
        // Parse double invariant
        double d = double.Parse(output, CultureInfo.InvariantCulture);
        Console.WriteLine(d);
    }
    

提交回复
热议问题