There is no magic going on here. It is only the form that information is being displayed that ends up confusing the user (developer). This is the way that float
is implemented, when you write 3.1415f
this is not the actual value that will be applied to the variable, it is not exactly the value found in memory according to the float
implementation. 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 receiving a "rounding", but the actual value found in the variable is not 3.1415f
. This "problem" is not very common to find when working with only floats
, but when there is value coercion from float
to double
people notice this difference because double
ends up displaying all the information, thus rendering the values 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 only characteristic of Java
, several languages implement this rule, and developers often suffer from this when they need a lot of precision. C # implements the same rules for float
and double
, when something needs a lot of precision as monetary values they have a decimal
implementation to meet those demands. Other languages such as JavaScript
have only one implementation to represent numbers, and they end suffering from this , ranging from problems accurately to representing large numbers, requiring libraries to solve the problem.