If I have a C# float
, can I convert it to double
without losing any precision?
If that double
were converted back to float
, would it have exactly the same value?
If I have a C# float
, can I convert it to double
without losing any precision?
If that double
were converted back to float
, would it have exactly the same value?
Yes. IEEE754 floating point (which is what C# must use) guarantees this:
Converting a
float
to adouble
preserves exactly the same valueConverting that
double
back to afloat
recovers exactly that originalfloat
.The set of
double
s is a superset offloat
s.Note that this also applies to
NaN
,+Infinity
, and-Infinity
. The signedness of zero is also preserved.Let's test this with code:
This code tests every
float
value betweenMinValue
andMaxValue
(exceptNaN
, infinities, etc...). The in-memory byte representation is compared to ensure no other conversions take place.Though it might seem crazy to test the ~4 billion possible floating point numbers, it actually runs in around 11 seconds on my machine.
And yes, the conversion is safe. Converting from float, to double, then back again doesn't lose any information.