Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal.Parse and incorrect string format error

Tags:

c#

.net

decimal

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);
like image 206
Tony Avatar asked Apr 09 '13 08:04

Tony


People also ask

What is decimal parse?

Parse(String) Converts the string representation of a number to its Decimal equivalent.


2 Answers

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);
like image 82
Martin Liversage Avatar answered Oct 13 '22 09:10

Martin Liversage


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);
like image 29
V4Vendetta Avatar answered Oct 13 '22 11:10

V4Vendetta