Why can't Double be implicitly cast to Decimal

后端 未结 3 692
青春惊慌失措
青春惊慌失措 2020-11-30 13:49

I don\'t understand the casting rules when it comes to decimal and double.

It is legal to do this

decimal dec = 10;
double doub = (double) dec;


        
相关标签:
3条回答
  • 2020-11-30 14:04

    Decimal is more precise, so you would lose information. That's why you can only do it explicitely. It's to protect you from losing information. See MSDN

    http://msdn.microsoft.com/en-us/library/678hzkk9%28v=VS.100%29.aspx

    http://msdn.microsoft.com/en-us/library/364x0z75.aspx

    0 讨论(0)
  • 2020-11-30 14:13

    You can explicitly cast in both directions: from double to decimal and from decimal to double.

    You can't implicitly convert in either direction for a very good reason: the conversion may not be loss-less.

    For example, the decimal number 1234567890123456789 can not be exactly represented as a double. Likewise, the double number 10^32 cannot be exactly represented as a decimal number.

    To avoid losing information unintentionally, the implicit conversion is disallowed.

    0 讨论(0)
  • 2020-11-30 14:23

    If you convert from double to decimal, you can lose information - the number may be completely out of range, as the range of a double is much larger than the range of a decimal.

    If you convert from decimal to double, you can lose information - for example, 0.1 is exactly representable in decimal but not in double, and decimal actually uses a lot more bits for precision than double does.

    Implicit conversions shouldn't lose information (the conversion from long to double might, but that's a different argument). If you're going to lose information, you should have to tell the compiler that you're aware of that, via an explicit cast.

    That's why there aren't implicit conversions either way.

    0 讨论(0)
提交回复
热议问题