Why c# decimals can't be initialized without the M suffix?

后端 未结 6 1145
一生所求
一生所求 2020-11-30 11:56
public class MyClass
{
    public const Decimal CONSTANT = 0.50; // ERROR CS0664   
}

produces this error:

error CS0664: Lit

6条回答
  •  没有蜡笔的小新
    2020-11-30 12:50

    From http://msdn.microsoft.com/en-us/library/364x0z75.aspx : There is no implicit conversion between floating-point types and the decimal type; therefore, a cast must be used to convert between these two types.

    They do this because double has such a huge range ±5.0 × 10−324 to ±1.7 × 10308 whereas int is only -2,147,483,648 to 2,147,483,647. A decimal's range is (-7.9 x 1028 to 7.9 x 1028) / (100 to 28) so it can hold an int but not a double.

提交回复
热议问题