Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

c# - Decimal.Parse and incorrect string format error

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...