简体   繁体   中英

Convert a negative string decimal value to double in c#

I want to convert a value in string format like -14.3 to double.

I am currently using Convert.ToDouble() to convert positive values to double but in case of negative decimal values it returns unexpected results. For -14.3 it returns -143 . So need some help in this regard

 private double getDouble(string Value)
        {
            double result = 0;
            try
            {               
                result = Convert.ToDouble(Value);                
            }
            catch (Exception)
            {
                result = 0;
            }

            return result;
        }

    }

You need to use NumberFormatInfo to specify the characters used for the negative sign and the decimal separator.

var format = new NumberFormatInfo();
format.NegativeSign = "-";
format.NumberDecimalSeparator = ".";

var negativeNumber = Double.Parse("-14.3", format); // -14.3
var positiveNumber = Double.Parse("352.6", format); // 352.6

See the code in action on repl.it .

Instead of using Convert.ToDouble function, use:

public static double mtdGetDouble(string Value)
{
    if (Value == "" || Value == "-") return 0;
    else return Convert.ToDouble(Value);
}

(It's my Style...)

If you want to use Double.TryParse with NumberFormatInfo you need to specify NumberStyles.AllowDecimalPoint and NumberStyles.AllowLeadingSign .

var format = new NumberFormatInfo();
format.NegativeSign = "-";
format.NumberNegativePattern = 1;
format.NumberDecimalSeparator = ".";

double negativeNumber;
Double.TryParse("-14.3", NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, format, out negativeNumber); // -14.3
double positiveNumber;
Double.TryParse("352.6", NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, format, out positiveNumber); // 352.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM