Java Puzzle #3: Rounding

· by

Contents

The puzzle

What is the output of the following script:

public class test {
    public static void main(String[] args) {
        double x = 0.4999999999999999;
        double y = 0.49999999999999992;
        double z = 0.49999999999999994;
        System.out.println(x + " rounded is " + Math.round(x));
        System.out.println(y + " rounded is " + Math.round(y));
        System.out.println(z + " rounded is " + Math.round(z));
    }
}

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Answer

0.4999999999999999 rounded is 0
0.49999999999999994 rounded is 1
0.49999999999999994 rounded is 1

Explanation

It's a bug.

See also: Why does Math.round(0.49999999999999994) return 1