简体   繁体   English

将负字符串十进制值转换为C#中的double

[英]Convert a negative string decimal value to double in c#

I want to convert a value in string format like -14.3 to double. 我想将字符串格式(如-14.3的值转换为double。

I am currently using Convert.ToDouble() to convert positive values to double but in case of negative decimal values it returns unexpected results. 我目前正在使用Convert.ToDouble()将正值转换为双Convert.ToDouble() ,但是如果十进制负数将返回意外结果。 For -14.3 it returns -143 . 对于-14.3它返回-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. 您需要使用NumberFormatInfo来指定用于负号和小数点分隔符的字符。

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 . 请参阅repl.it上的代码

Instead of using Convert.ToDouble function, use: 代替使用Convert.ToDouble函数,使用:

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 . 如果要将Double.TryParseNumberFormatInfo一起使用,则需要指定NumberStyles.AllowDecimalPointNumberStyles.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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