小数.Parse抛出FormatException
本文关键字:FormatException 抛出 Parse 小数 | 更新日期: 2023-09-27 18:03:04
我尝试使用小数。解析如下所述: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,你知道为什么会这样吗?
谢谢,eyal
树。Pat18的回答当然是对的。但是如果你允许的话,我想再多解释一下这个问题。
让我们看看Decimal.ToParse(string)
方法如何实现;
public static Decimal Parse(String s)
{
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
可以看到,该方法默认使用NumberStyles.Number
。它是一个合数样式,实现方式为;
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)
重载,因为你可以自己指定NumberStyles
。
试试这个:
using System.Globalization;
using System.Text;
....
number = Decimal.Parse(value, NumberStyles.AllowExponent|NumberStyles.AllowDecimalPoint);
为了以指数格式解析数字,您需要设置NumberStyles Enumeration
中的适当标志,如下所示。