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.

Best Solution

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.