C#decimal.Parse和不正确的字符串格式错误 [英] C# decimal.Parse and incorrect string format error

查看:537
本文介绍了C#decimal.Parse和不正确的字符串格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,小数解析。下面code正常工作,我的电脑上,但是当我发布项目在服务器上(VPS,在Windows Server 2008 R2标准版),我得到的错误输入字符串的格式不正确。任何想法有什么不对?

我店,在MySQL数据库表分析号码 - 列类型为 DECIMAL(10,4)

来源$ C ​​$ C:

 的CultureInfo nonInvariantCulture =新的CultureInfo(EN-AU); //或PL-PL
nonInvariantCulture.NumberFormat.NumberDecimalSeparator =。;
Thread.CurrentThread.CurrentCulture = nonInvariantCulture;
串toConvert =(3,4589)更换(,,。)。 //这是一个例子
十进制解析= decimal.Parse(toConvert);
 

解决方案

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

  VAR数=3,4589;
VAR的NumberFormatInfo =新的NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator =,;
VAR值= Decimal.Parse(数的NumberFormatInfo);
 

您也可以使用的CultureInfo ,你知道会工作,但我认为这是比较容易理解。

如果在另一方面号码的格式为: 3.4589 您可以简单地使用 CultureInfo.InvariantCulture 您可以考虑一种基于的en-US 默认文化:

  VAR数=3.4589;
VAR值= Decimal.Parse(数量,CultureInfo.InvariantCulture);
 

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?

I store that parsed number in the MySQL DB table - the column type is 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);

解决方案

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();
numberFormatInfo.NumberDecimalSeparator = ",";
var value = Decimal.Parse(number, numberFormatInfo);

You can also use a CultureInfo that you know will work but I think this is easier to understand.

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

这篇关于C#decimal.Parse和不正确的字符串格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆