21

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);
3
  • 2
    Are you sure the machine in question has en-AU (or pl_PL) cultures installed? On a fresh install, most machines have only the english subsets installed by default. Commented Apr 9, 2013 at 8:41
  • whether is this windows or web application ? Commented Apr 9, 2013 at 8:54
  • Ramesh Muthiah >> it's web application Commented Apr 9, 2013 at 9:03

3 Answers 3

45

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);
Sign up to request clarification or add additional context in comments.

Comments

6

I guess for a work around the below code will sort it out the problem.

decimal parsed = decimal.Parse(toConvert, CultureInfo.InvariantCulture);

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.