0
    double a = 99.99;
    double b = 1.05;
    double dsum = a + b;
    double dsub = a-b;
    System.out.println(dsum); //101.03999999999999
    System.out.println(dsub); //98.94

    float c = 99.99f;
    float d = 1.05f;
    float fsum = c+d;
    float fsub = c-d;
    System.out.println(fsum); //101.04
    System.out.println(fsub); //98.939995

Check these additions and subtractions. Can someone explain why is there results like these with numbers ending with 9. My application is dealing with money so error of even .001 is not acceptable. In IOS swift also there is this issue but when using Decimal it works fine.

One theory is that decimal and and float save 1 as 0.99999, thus 1.05 becomes 1.04999(hence giving 101.03999) but then why is this not consistent with all values?

Ashwani Kumar
  • 1,402
  • 1
  • 19
  • 26
  • With floating point the number 1 can be represented exactly, but numbers like 0.05 and 99.99 can only be approximated. You should use [`BigDecimal`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/math/BigDecimal.html) to represent money values – Thomas Kläger Feb 17 '22 at 09:31
  • Three things you should know: (1) Java’s `Number` type uses base-two floating-point. Each number representable in it is an integer less than 2^53 times a power of two (like 3•2^−2 for 3/4) or its negative. (2) The result of each elementary operation is the real-number result rounded to the nearest representable value. This includes converting decimal numerals in source code to `Number`, so `1.05` produces 1.0500000000000000444089209850062616169452667236328125. (3) Java output lies about their values. Its default formatting produces just enough digits to uniquely distinguish the `Number` value. – Eric Postpischil Feb 17 '22 at 09:44

0 Answers0