How to Convert string ("0.25500000") less than 1 to Decimal?

273 views Asked by At

I have a string "0.30405" and I need to convert it to a decimal. However it's throwing an error.

What is the solution for this without blowing my head off

Convert.ToDecimal("0.25500000") //throws exception
3

There are 3 answers

2
Håkan Fahlstedt On

If that line throws an exception, it's probably because your culture settings doesn't allow comma as decimal separator.

0
Ondrej Svejdar On

Try

Convert.ToDecimal("0.25500000", CultureInfo.InvariantCulture);
1
Ondrej Janacek On

Try using decimal.TryParse() with a culture info specified.

decimal number;
decimal.TryParse("0.25500000", NumberStyles.Number, 
                  CultureInfo.InvariantCulture, out number);

As someone pointed out in comments, in a production code you would probably want to find out if a conversion is successful by

if(decimal.TryParse(...))
{
    // success
}