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

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

提交回复
热议问题