This question already has answers here:
Closed 6 years ago.
Could you please explain, why I got next result:
when I run this:
System.out.println((0.2 - 0.1));
I got: 0.1
when I run this:
System.out.println((0.3 - 0.2));
I got: 0.09999999999999998
I know that number "0.1" doesn't have finite representation in binary, but it doesn't explain the results above. Most likely this is not about particular language but about how digits are stored in computer.
Java uses IEEE floating point to represent double
values. It is not a precise representation, and some calculations result in tiny errors that manifest themselves in this way.
I agree with Bohemian above (float
and double
is not precise) so you will get oddities like this
but there is a solution for your problem:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(0.3f - 0.2f);
This will produce 0.1
.