-2

When I try to get the answer for the (14.99 + 1.5) and (15.99 + 1.5) my programs gives me the different output which I didn't expect. Any reason for that?

Here is my simple program:

class Demo {
    public static void main(String[] args) {

        System.out.println(12.99 + 1.5);           
        System.out.println(13.99 + 1.5);           
        System.out.println(14.99 + 1.5);           
        System.out.println(15.99 + 1.5);           
        System.out.println(16.99 + 1.5);           

    }
}

Here is the output : enter image description here

My JDK version : 1.7.0_25

  • Down votes Seriously?? I don't ask this question if i know the reason for this and this is the 1st time i'm experiencing this kind of output. Actually I din't know there is a same kind of question already and it has a completely different title compared to mine. So I din't see that question while searching for a solution. Thank you for understanding.. – Chamithra Thenuwara Dec 27 '14 at 11:06

1 Answers1

2

my programs gives me the wrong output.

This is the right output for double, just not what you expected.

Floating point approximates values which it cannot represent accurately. In this case 1.5 is accurately represented as a sum or powers of two 2^0 + 2^-1, however 12.99 need to be approximated. When you print a floating point numebr it "knows" the number is approximate and needs to be rounded to to simplest number which would have that repesentation i.e. 14.49 happens to be what you expected. The value for 14.99 + 1.5 is a little bit too small and you see the representation error i.e. the illusion of exact values is lifted.

When you do floating point, you need to provide the expected rounding as well and you will get the expected answer (within bounds, very large numbers will still be wrong with rounding as double has limited precision)

    System.out.printf("%.2f%n", 12.99 + 1.5);           
    System.out.printf("%.2f%n", 13.99 + 1.5);           
    System.out.printf("%.2f%n", 14.99 + 1.5);           
    System.out.printf("%.2f%n", 15.99 + 1.5);           
    System.out.printf("%.2f%n", 16.99 + 1.5);

prints

 14.49
 15.49
 16.49
 17.49
 18.49

as expected.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130