0

I read a book about Java and I've faced a strange issue. Would be really nice if you help me to figure what's going on :).. Take a look on the code please:

class Promote {
    public static void main (String args[]) {
        byte b = 42;
        char c = 'a';
        short s = 1024;
        int i = 50000;
        float f = 5.67f;
        double d = .1234;
        double x = 238.14 + 515 - 126.3616;
        double result = (f * b) + (i / c) - (d * s); // (5.67 * 42) + (50000 / 97) - (0.1234 * 1024)
        System.out.println((f * b) + " + " + (i / c) + " - " + (d * s) + " = " + result); // 238.14 + 515 - 126.3616 = 626.7784
    }
}

My calculations in comments seems to be logical, but the actual output is 626.7784146484375 I've no clue why do I've this 0.0000146484375 difference. Make it clear for me please! Thank you.

Mike
  • 1,979
  • 2
  • 16
  • 29
  • 2
    Especially important from Todd's link: [What every computer scientist should know about floating point.](http://docs.sun.com/source/806-3568/ncg_goldberg.html) – markspace Jan 05 '15 at 00:54
  • @markspace + Todd, already reading it. Thank you very much! – Mike Jan 05 '15 at 00:58
  • 2
    If your application requires decimal precision use [`BigDecimal`](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html) class. – PM 77-1 Jan 05 '15 at 00:59

0 Answers0