7

Possible Duplicate:
Retain precision with Doubles in java
Moving decimal places over in a double

For example, something as simple as this:

public class WrongAnswer {
  public static void main(String[] args) {
    System.out.println(100*1.1);
  }
}

prints 110.00000000000001 instead of 110. Using other numbers instead of 100*1.1 also give a lot of digits with some random digit at the end that isn't right..

Any ideas?

Community
  • 1
  • 1
Nate
  • 117
  • 1
  • 2
  • 7

4 Answers4

9

Floating point notations have limited degrees of accuracy. Here's a guide: http://floating-point-gui.de/

CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58
4

Most floating point calculations involve rounding errors. In your case, there are two rounding errors: converting (decimal) 1.1 to floating point (there's no exact representation for 1.1 in IEEE 754 floating point--which is what Java uses) and then multiplying by 100. See the excellent article What Every Computer Scientist Should Know About Floating-Point Arithmetic for more info.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
3

In 100*1.1 the 1.1 is not qualified and so by default is double while 100 is by default int.
So the result of the multiplication is also double due to the upcast of 100 and that is why you get this result.

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • The cast to `int` happens to work here, but only by accident. In other contexts you could end up with one less than you expect. – Ted Hopp Oct 22 '12 at 21:43
  • 100.0d * 1.1d gives same result (110.00000000000001) – chrome Oct 22 '12 at 21:53
  • but float no problem :) 100.0f * 1.1f (110.0) – chrome Oct 22 '12 at 21:55
  • It is certainly not 'due to the upcast of 100'. The fact that 100 is an int isn't even relevant. As one of the operands is a double, the calculation is always going to be carried out as double. – user207421 Oct 22 '12 at 22:30
  • @EJP:In order for the calculation to be carried as `double` *both* operands should be double and that means that `100` first is *converted* to a `double` as a result of `binary numeric promotion`.And I did not say this is due to `upcast of 100`.But due to `1.1` being `double` and therefore `100` being widened to carry out the multiplication.Please read more carefully if you plan to downvote – Cratylus Oct 23 '12 at 16:56
0

As answered, it becomes double hence the format. To print the closest int/long value, better to use Math.round() function as :

 System.out.println(Math.round(100*1.1));

This becomes important when you are multiplying with more precise numbers e.g.

    System.out.println(Math.round(100*1.199));  //--> prints 112
    System.out.println((int)(100*1.199)); //--> prints 111
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73