为什么不能将Double隐式转换为Decimal

为什么不能将Double隐式转换为Decimal

本文介绍了为什么不能将Double隐式转换为Decimal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于小数和双精度数,我不了解强制转换规则。



这样做是合法的

 十进制dec = 10; 
double doub =(double)dec;

但是令我困惑的是十进制是16字节数据类型,而double是8字节,所以不是将双精度型转换为十进制,以扩大对话范围,因此应隐式允许;与上面的示例不允许?

解决方案

如果从 double 转换为十进制,您可能会丢失信息-该数字可能完全超出范围,因为 double 的范围比a的范围大得多十进制



如果从十进制转换为 double ,您可能会丢失信息-例如,0.1可以精确表示为十进制,而不能表示为 double 和十进制实际上比 double 使用更多的精度。 / p>

隐式转换不应丢失信息(从 long double 可能,但这是一个不同的参数)。如果您要丢失信息,则必须通过显式强制转换告诉编译器您已经知道这一点。



这就是为什么没有两种方式都可以进行隐式转换。


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;

What confuses me however is that decimal is a 16 byte datatype and double is 8 bytes so isn't casting a double to a decimal a widening conversation and should therefore be allowed implicitly; with the example above disallowed?

解决方案

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.

这篇关于为什么不能将Double隐式转换为Decimal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:04