3

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.

XZen
  • 225
  • 5
  • 27
  • 49
  • 4
    [Mandatory Link](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Steve P. Dec 09 '13 at 12:02
  • 2
    Removed "Irrational" from title, as the term "irrational number" has a specific meaning which has nothing to do with the question. – Ingo Dec 09 '13 at 12:11

2 Answers2

1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207