Decimal.Parse和不正确的字符串格式错误 [英] Decimal.Parse and incorrect string format error
问题描述
我对十进制解析有一个简单的问题。以下代码在我的计算机上工作正常,但是当我在服务器(VPS,Windows Server 2008 R2标准版)上发布项目时,出现错误输入字符串格式错误。任何想法有什么问题吗?
I have a simple problem with decimal parsing. The following code works fine on my computer but when I publish the project on the server (VPS, Windows Server 2008 R2 standard edition) I get the error "Input string was in incorrect format." Any ideas what's wrong?
我将解析后的数字存储在MySQL DB表中-列类型为 DECIMAL(10,4)
I store that parsed number in the MySQL DB table - the column type is DECIMAL(10, 4)
源代码:
CultureInfo nonInvariantCulture = new CultureInfo("en-AU"); //or pl-PL
nonInvariantCulture.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = nonInvariantCulture;
string toConvert = ("3,4589").Replace(",", "."); //it's an example
decimal parsed = decimal.Parse(toConvert);
推荐答案
如果您知道数字的字符串表示形式使用逗号作为小数点分隔符,您可以使用自定义 NumberFormatInfo
:
If you know that the string representation of the number uses comma as the decimal separator you can parse the value using a custom NumberFormatInfo
:
var number = "3,4589";
var numberFormatInfo = new NumberFormatInfo { NumberDecimalSeparator = "," };
var value = Decimal.Parse(number, numberFormatInfo);
您也可以将现有的 CultureInfo
用于您知道的文化会像 pl-PL
一样工作,但我认为这更容易理解。
You can also use an existing CultureInfo
for a culture that you know will work like pl-PL
but I think this is easier to understand.
如果另一方面,数字的格式为 3.4589
,您可以简单地使用 CultureInfo.InvariantCulture
,您可以将其视为基于 en-US
的默认文化:
If on the other hand the format of the number is 3.4589
you can simply use CultureInfo.InvariantCulture
which you can consider a kind of "default" culture based on en-US
:
var number = "3.4589";
var value = Decimal.Parse(number, CultureInfo.InvariantCulture);
这篇关于Decimal.Parse和不正确的字符串格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!