C# 转换结尾带负号的字符串中的数字

C# 转换结尾带负号的字符串中的数字,c#,numbers,C#,Numbers,从MSDN文档中,我应该使用NumberFormatInfo的NumberNegativePattern属性设置负数值的预期模式 所以我试着: var format = new NumberFormatInfo {NumberNegativePattern = 3}; Console.WriteLine(Convert.ToDouble("1.000-", format)); 但我总是收到一个FormatException,说“输入字符串的格式不正确”。我还尝试了使用NumberFormatI

从MSDN文档中,我应该使用NumberFormatInfo的NumberNegativePattern属性设置负数值的预期模式

所以我试着:

var format = new NumberFormatInfo {NumberNegativePattern = 3};
Console.WriteLine(Convert.ToDouble("1.000-", format));

但我总是收到一个FormatException,说“输入字符串的格式不正确”。我还尝试了使用NumberFormatInfo.InvariantInfo进行格式化,结果相同。

这里不需要格式-看起来
NumberNegativePattern
仅在格式化时使用,而不是解析,然后仅用于
N
格式。但是,有一个
NumberStyles
值:

Console.WriteLine(double.Parse("1.000-", 
    NumberStyles.AllowTrailingSign | NumberStyles.AllowDecimalPoint));

您的
NumberFormatInfo
NumberNegativePattern
已分配给3,但
NumberFormatInfo
的其他属性将取决于您的
CurrentCulture
。但这不是重点

Convert.ToDouble(字符串,IFormatProvider)
方法为

并按以下方式实施:

public static double Parse(String s, IFormatProvider provider)
{
   return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
并且没有
numberstyle.AllowTrailingSign
,这就是代码抛出的原因


很难判断你的
1.000
值是带小数点的
1
还是带千位分隔符的
1000
,但是你可以使用
AllowDecimalPoint
AllowThousands
样式,并将
AllowTrailingSign
样式作为我们的第二个参数。

public static double Parse(String s, IFormatProvider provider)
{
   return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}