Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c# - Why can't Double be implicitly cast to Decimal

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?

double doub = 3.2;
decimal dec = doub; // CS0029: Cannot implicitly convert type 'double' to 'decimal'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...