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

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

    The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.

    double val;
    
    if (temp.Text.Split('.').Length > 1)
    {
        val = double.Parse(temp.Text.Split('.')[0]);
    
        if (temp.Text.Split('.')[1].Length == 1)
            val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
        else
            val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
    }
    else
        val = double.Parse(RR(temp.Text));
    
    0 讨论(0)
  • 2020-11-22 07:11

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

    List<string> inputs = new List<string>()
    {
        "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);
    }
    
    0 讨论(0)
  • 2020-11-22 07:17

    Look, every answer above that proposes writing a string replacement by a constant string can only be wrong. Why? Because you don't respect the region settings of Windows! Windows assures the user to have the freedom to set whatever separator character s/he wants. S/He can open up the control panel, go into the region panel, click on advanced and change the character at any time. Even during your program run. Think of this. A good solution must be aware of this.

    So, first you will have to ask yourself, where this number is coming from, that you want to parse. If it's coming from input in the .NET Framework no problem, because it will be in the same format. But maybe it was coming from outside, maybe from a external server, maybe from an old DB that only supports string properties. There, the db admin should have given a rule in which format the numbers are to be stored. If you know for example that it will be an US DB with US format you can use this piece of code:

    CultureInfo usCulture = new CultureInfo("en-US");
    NumberFormatInfo dbNumberFormat = usCulture.NumberFormat;
    decimal number = decimal.Parse(db.numberString, dbNumberFormat);
    

    This will work fine anywhere on the world. And please don't use 'Convert.ToXxxx'. The 'Convert' class is thought only as a base for conversions in any direction. Besides: You may use the similar mechanism for DateTimes too.

    0 讨论(0)
  • 2020-11-22 07:23

    Here is a solution that handles any number string that many include commas and periods. This solution is particular for money amounts so only the tenths and hundredths place are expected. Anything more is treated as a whole number.

    First remove anything that is not a number, comma, period, or negative sign.

    string stringAmount = Regex.Replace(originalString, @"[^0-9\.\-,]", "");
    

    Then we split up the number into the whole number and decimal number.

    string[] decimalParsed = Regex.Split(stringAmount, @"(?:\.|,)(?=\d{2}$)");
    

    (This Regex expression selects a comma or period that is two numbers from the end of the string.)

    Now we take the whole number and strip it of any commas and periods.

    string wholeAmount = decimalParsed[0].Replace(",", "").Replace(".", "");
    
    if (wholeAmount.IsNullOrEmpty())
            wholeAmount = "0";
    

    Now we handle the decimal part, if any.

    string decimalAmount = "00";
    
    if (decimalParsed.Length == 2)
        {
            decimalAmount = decimalParsed[1];
        }
    

    Finally we can put the whole and decimal together and parse the Double.

    double amount = $"{wholeAmount}.{decimalAmount}".ToDouble();
    

    This will handle 200,00, 1 000,00 , 1,000 , 1.000,33 , 2,000.000,78 etc.

    0 讨论(0)
  • 2020-11-22 07:24
            var doublePattern = @"(?<integer>[0-9]+)(?:\,|\.)(?<fraction>[0-9]+)";
            var sourceDoubleString = "03444,44426";
            var match = Regex.Match(sourceDoubleString, doublePattern);
    
            var doubleResult = match.Success ? double.Parse(match.Groups["integer"].Value) + (match.Groups["fraction"].Value == null ? 0 : double.Parse(match.Groups["fraction"].Value) / Math.Pow(10, match.Groups["fraction"].Value.Length)): 0;
            Console.WriteLine("Double of string '{0}' is {1}", sourceDoubleString, doubleResult);
    
    0 讨论(0)
  • 2020-11-22 07:25

    The trick is to use invariant culture, to parse dot in all cultures.

    double.Parse("3.5", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);
    
    0 讨论(0)
提交回复
热议问题