Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to double loses precision but not via ToString

Tags:

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?

like image 715
JoshG Avatar asked May 13 '11 03:05

JoshG


People also ask

Can you convert a float to a double?

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 .

Can you convert a float to a string?

We can convert float to a string easily using str() function.

Can we convert float to long in Java?

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.

Can you convert a float to a double in C?

You can't convert from float to double and except that float will have the same precision of double.


1 Answers

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 " 
like image 179
rerun Avatar answered Nov 17 '22 14:11

rerun