C# 为什么在有效的双输入上接收FormatException?
我收到FormatException,我不知道为什么C# 为什么在有效的双输入上接收FormatException?,c#,C#,我收到FormatException,我不知道为什么 System.FormatException was unhandled by user code Message=Input string was not in a correct format. Source=mscorlib StackTrace: at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo
System.FormatException was unhandled by user code
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Convert.ToDouble(String value)
代码行:
DELTA_BUY = Convert.ToDouble(parameters["DELTA_BUY"]);
值(从调试窗口):
upd在一条执行路径上工作正常,但在另一条执行路径上失败(当来自WCF时)。可在双音上复制,可与字符串配合使用。可能是格式/国有化问题?字符串本身是否包含双引号?解析器将无法转换带有嵌入引号的字符串。除此之外,我看不出为什么包含该值的字符串在en-US区域性或不变区域性中不能作为double进行解析 在其他文化中,小数点不能用于标记数字中的“零次幂”。例如,France(fr)通常使用逗号,而千位分隔符是一个空格。在任何存在此类差异的文化中,尝试解析此字符串都将失败。您可以通过在执行转换时指定特定区域性来避免这种情况,您知道该区域性将处理所使用的数字格式:
//this will definitely work, as the en-US culture would definitely be able
//to parse this number string.
DELTA_BUY = Convert.ToDouble(parameters["DELTA_BUY"], new CultureInfo("en-US"));
//this SHOULD work, and is generally more proper than forcing use of the US
//culture's formatter in a program otherwise designed to work in, say, Italy.
DELTA_BUY = Convert.ToDouble(parameters["DELTA_BUY"], CultureInfo.InvariantCulture);
不变区域性描述通用英语区域性(在小数中使用小数点),并应强制系统忽略可能不使用小数点分隔整个数字和小数部分的任何特定区域性。您的计算机是否可能设置为“0.0016”的区域性这不是一个有效的数字吗? 试一试
可能是区域设置问题、线程语言或其他相关问题。如果您总是使用
作为十进制分隔符接收数据,则可以使用以下方法:
Convert.ToDouble("0.0016", new NumberFormatInfo{ NumberDecimalSeparator = "."});
你的区域设置如何?@RubensFarias是的,可能就是这样。但有趣的是,在一条执行路径上,它运行良好。在另一个执行路径上失败(更新的描述)。我不知道在哪里检查/调整区域设置这两个路径中是否都是相同的字符串?@DaveShaw它是通过相同的代码从静态文件读取的,因此我几乎99.99%确定它们是相同的,字符串本身不包含双引号,我想这是调试窗口表示hmm。。。出于好奇,你的机器使用的是什么文化?英国文化正确地解读了这一点,欧洲大陆文化会将其解读为16(而不是抛出)…我猜可能是英语或俄罗斯文化,因为我在系统上安装了这两种语言。是的,刚刚测试了用ru-ru解析它,它抛出。
DELTA_BUY = Convert.ToDouble(parameters["DELTA_BUY"], System.Globalization.CultureInfo.InvariantCulture);
Convert.ToDouble("0.0016", new NumberFormatInfo{ NumberDecimalSeparator = "."});