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);
Parse(String) Converts the string representation of a number to its Decimal equivalent.
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);
You can build a custom NumberFormatInfo
to parse your value
something on these lines
NumberFormatInfo numinf = new NumberFormatInfo();
numinf.NumberDecimalSeparator= ",";
decimal.Parse("3,4589", numinf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With