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?

2
  • 5
    welcome to the wonderful world of floating point numbers, where everything is approximate and the decimals don't matter. Commented Oct 22, 2012 at 21:40
  • Duplicate stackoverflow.com/search?q=java+double+precision Commented Oct 22, 2012 at 21:46

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

5 Comments

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.
100.0d * 1.1d gives same result (110.00000000000001)
but float no problem :) 100.0f * 1.1f (110.0)
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.
@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
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

1 Comment

@NegativeUser: Please leave some comment to understand the issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.