C# Decimal.Parse 和不正确的字符串格式错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15897134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:20:23  来源:igfitidea点击:

Decimal.Parse and incorrect string format error

c#.netdecimal

提问by Tony

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?

我有一个十进制解析的简单问题。以下代码在我的计算机上运行良好,但是当我在服务器(VPS、Windows Server 2008 R2 标准版)上发布项目时,出现错误“输入字符串的格式不正确”。任何想法有什么问题?

I store that parsed number in the MySQL DB table - the column type is DECIMAL(10, 4)

我将解析后的数字存储在 MySQL 数据库表中 - 列类型是 DECIMAL(10, 4)

Source Code:

源代码:

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);

采纳答案by Martin Liversage

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:

如果您知道数字的字符串表示使用逗号作为小数点分隔符,您可以使用自定义来解析该值NumberFormatInfo

var number = "3,4589";
var numberFormatInfo = new NumberFormatInfo { NumberDecimalSeparator = "," };
var value = Decimal.Parse(number, numberFormatInfo);

You can also use an existing CultureInfofor a culture that you know will work like pl-PLbut I think this is easier to understand.

您也可以将现有CultureInfo的文化用于您知道会起作用的文化,pl-PL但我认为这更容易理解。

If on the other hand the format of the number is 3.4589you can simply use CultureInfo.InvariantCulturewhich you can consider a kind of "default" culture based on en-US:

另一方面,如果数字的格式是3.4589您可以简单地使用CultureInfo.InvariantCulture它,您可以考虑一种基于以下内容的“默认”文化en-US

var number = "3.4589";
var value = Decimal.Parse(number, CultureInfo.InvariantCulture);

回答by V4Vendetta

You can build a custom NumberFormatInfoto parse your value

您可以构建自定义NumberFormatInfo来解析您的值

something on these lines

这些线上的东西

NumberFormatInfo numinf = new NumberFormatInfo();
numinf.NumberDecimalSeparator= ",";    
decimal.Parse("3,4589", numinf);

回答by Smaug

I guess for a work around the below code will sort it out the problem.

我想解决以下代码可以解决问题。

decimal parsed = decimal.Parse(toConvert, CultureInfo.InvariantCulture);