当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: