gpt4 book ai didi

c# - 为什么转换这个指数会抛出 FormatException?

转载 作者:行者123 更新时间:2023-11-30 22:13:45 26 4
gpt4 key购买 nike

为什么这个指数在使用 Decimal.Parse 转换为小数时会抛出 FormatException

String stringValue = "8.83080183680678E-05";
Decimal decimalValue = Decimal.Parse(badValue, NumberStyles.AllowExponent);

当代码执行时抛出一个FormatException

"Input string was not in a correct format."

代码似乎遵守 MSDN spec : [ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][ws]

最佳答案

您需要指定数字格式也允许小数。

Decimal.Parse(badValue, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);

...在 AllowExponent 的文档中有解释:

Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.

NumberStyles.Float 在这种情况下可能是更好的选择。

关于c# - 为什么转换这个指数会抛出 FormatException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18881639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com