• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #3: Rounding

Contents

  • Java Puzzle #3: Rounding
    • The puzzle
    • Answer
    • Explanation

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


Published

Jul 17, 2012
by Martin Thoma

Category

Code

Tags

  • Java 36
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor