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
329 views
in Technique[技术] by (71.8m points)

c# - Does casting double to float always return same value?

Does casting double to float always produce same result, or can there be some "rounding differences"?

For example, is x in

float x = (float)0.123456789d;

always the same value?

What about when casting float to double, and then casting it back to float ie. (float)(double)someFloat ?

Mostly interested in what the results are in C#, but feel free to share if you have knowledge about how this works on other languages.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The results should not be language dependent, unless the language deviates from the IEEE specification.

All floats can be exactly represented as doubles, so the round trip from float to double to float should yield the same value that you started with.

Similarly, casting any double value to float should always yield the same result, but, of course, there are many different double values that would truncate to the same float value.


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

...