The way Java prints floating-point numbers is a significant part of the behavior you are seeing: By default, Java does not print the exact value of a floating-point number. It prints just enough digits to precisely identify the double
that is being printed.
Thus, if you set x
to .3
, x
is actually set to 0.299999999999999988897769753748434595763683319091796875. When Java prints this, it prints only “.3”, because converting “.3” to double
yields the value of x
, 0.299999999999999988897769753748434595763683319091796875.
When you use .1
and .2
, these are actually the values 0.1000000000000000055511151231257827021181583404541015625 and 0.200000000000000011102230246251565404236316680908203125. When you add them (in double
format), the result is 0.3000000000000000444089209850062616169452667236328125.
When you print this value, Java prints “0.30000000000000004” because it needs to show all those digits in order to produce a numeral that, when converted back to double
, will produce 0.3000000000000000444089209850062616169452667236328125.
Here is the documentation for how double
values are printed. It says:
How many digits must be printed for the fractional part…? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double
.
repr
does.str
does not. – Wooble{:.20f}".format(0.1)
– Ricardo Cárdenes