c# - Decimal.Parse 抛出 FormatException

标签 c# decimal formatexception

我尝试使用 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,

这意味着您的字符串可以具有以下之一;

由于 NumberStyles.NumberAllowDecimalPoint,它适合 . 在你的字符串中,但这种风格没有 AllowExponent 这就是它无法解析字符串中的 e-02 的原因。

这就是为什么你需要使用 Decimal.Parse Method (String, NumberStyles) overload因为您可以自己指定 NumberStyles

关于c# - Decimal.Parse 抛出 FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23604657/

相关文章:

c# - 排序的特殊性

c# - PrincipalContext Active Directory 验证容器中的用户

c# - Twilio API 请求限制/限制?

c - 函数无法运行(我的第一个 C 项目)

c# - DRY 字符串格式

C# DLLImport 'Complex' 数组返回和参数

javascript - 如何在javascript中处理大数字

SQL格式自四舍五入开始删除小数

C# FormatException double.parse(),为什么 0.89 不解析?

c# - 输入字符串的格式不正确