我尝试使用 decimal.parse,如下所述: http://msdn.microsoft.com/en-us/library/cafs243z(v=vs.110).aspx
所以我从这个页面复制了下面的例子:
string value;
decimal number;
value = "1.62345e-02";
try
{
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
}
catch (FormatException)
{
Console.WriteLine("Unable to parse '{0}'.", value);
}
我得到了一个 FormatException, 您知道为什么会这样吗?
谢谢, 艾亚尔
最佳答案
shree.pat18's answer当然是对的。但是如果你允许的话,我想稍微解释一下这个问题..
让我们看看如何Decimal.ToParse(string)
method implemented ;
public static Decimal Parse(String s)
{
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
如您所见,此方法使用 NumberStyles.Number
默认情况下。它是一种合数样式,它是implemented。喜欢;
Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowDecimalPoint | AllowThousands,
这意味着您的字符串可以具有以下之一;
- 前导和尾随空格(其中
Char.IsWhiteSpace
返回true
) - 当前区域性的前导或尾随符号(
PositiveSign
和NegativeSign
) - 您当前的文化
NumberDecimalSeparator
- 您当前的文化
NumberGroupSeparator
由于 NumberStyles.Number
有 AllowDecimalPoint
,它适合 .
在你的字符串中,但这种风格没有 AllowExponent
这就是它无法解析字符串中的 e-02
的原因。
这就是为什么你需要使用 Decimal.Parse Method (String, NumberStyles)
overload因为您可以自己指定 NumberStyles
。
关于c# - Decimal.Parse 抛出 FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23604657/