Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...