Convert UInt32 to float without rounding?

I need to convert a UInt32 type to a float without having it rounded. Say I do

float num = 4278190335;
uint num1 = num;

The value instantly gets changed to 4278190336. Is there any way around this?

Jon Skeet
people
quotationmark

I need to convert a UInt32 type to a float without having it rounded.

That can't be done.

There are 232 possible uint values. There are fewer than 232 float values (there are 232 bit patterns, but that includes various NaN values). Add to that the fact that there are obviously a lot of float values which can't be represented as uint (e.g. 0.5) and it becomes clear that you can't represent every uint value exactly in a float. However, every uint (and every int) can be represented exactly as a double, so that might be a solution to your problem.

The problem you're seeing in your original source code is that 4278190335 isn't exactly representable as a float; the closest float value is 4278190336. This isn't a problem with the conversion from float to uint - it's a problem with the conversion from the exact value you've specified in your source code into a float; the float to uint conversion happens separately (and again, can easily lose information).

people

See more on this question at Stackoverflow