问题描述:

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

网友答案:

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

网友答案:

Try

Convert.ToDecimal("0.25500000", CultureInfo.InvariantCulture);
网友答案:

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
}
相关阅读:
Top