No magic is happening here. It is only the way the information is being displayed that ends up confusing the user (developer). That’s the way the float
is implemented when you write 3.1415f
this is not the real value that will be applied to the variable, this is not exactly the value found in memory as the implementation of float
. You can perform some tests:
float a = 3.1415f;
float b = 3.1414999961853027f;
System.out.println("a = " + a); // a = 3.1415
System.out.println("b = " + b); // b = 3.1415
System.out.println(a == b); // true
The value displayed for both cases receives a "rounding", but the actual value found in the variable is not 3.1415f
. This "problem" is not very common to find when working only with floats
, but when there is the value coercion of a float
for a double
people notice this difference because the double
ends up displaying all the information, thus appearing that the values are different (when in fact they are not).
double c = a;
System.out.println("c = " + c); // c = 3.1414999961853027
You can see here a few more tests proving that both values are exactly the same.
NOTE: This is not something characteristic only of Java
, Several languages implement this standard and developers often struggle with it when they need a lot of precision. C# implements the same standards for float
and the double
, when something needs a lot of precision like monetary values they have an implementation decimal
to meet these demands. Other languages such as JavaScript
have only one implementation to represent numbers, and end suffering from it, from problems with precision to the representation of large numbers, requiring libraries to solve the problem.
"but when there is value coercion from a float to a double" - I think you meant "conversion," that would be?
– user28595
@diegofm "coercion" is implicit conversion, which is the case with the question. Of course, using the term "conversion" makes it more comprehensive, but I find it strange that people want to perform an explicit conversion (cast) between "float" and "double".
– Gabriel Katakura
Oh yes, it was only for "conscience disenchantment" even :) By the way, good answer, took away the doubt too +1
– user28595
@diegofm Yes, you are completely correct in questioning. If you think there is something wrong always question. ;)
– Gabriel Katakura
@Bacco reply edits, thanks for the link ;)
– Gabriel Katakura