I have the following code:
float f = 0.3f; double d1 = System.Convert.ToDouble(f); double d2 = System.Convert.ToDouble(f.ToString());
The results are equivalent to:
d1 = 0.30000001192092896; d2 = 0.3;
I'm curious to find out why this is?
The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .
We can convert float to a string easily using str() function.
The first way to convert a float data type into a long value is to auto-box float primitive into Float object and calls the longValue() method. This is a more structured way as other ways are simply to cast a float to long or int to get rid of decimal points.
You can't convert from float to double and except that float will have the same precision of double.
Its not a loss of precision .3 is not representable in floating point. When the system converts to the string it rounds; if you print out enough significant digits you will get something that makes more sense.
To see it more clearly
float f = 0.3f; double d1 = System.Convert.ToDouble(f); double d2 = System.Convert.ToDouble(f.ToString("G20")); string s = string.Format("d1 : {0} ; d2 : {1} ", d1, d2);
output
"d1 : 0.300000011920929 ; d2 : 0.300000012 "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With