-1
double double1 = 0.174;
double double2 = 0.175;
double diff = Math.abs(double1 - double2);

diff returns 0.0010000000000000009

Now I type:

double double1 = 3.174;
double double2 = 3.175;
double diff = Math.abs(double1 - double2);

I am expecting diff to return the same result, but it returns 9.999999999998899E-4. Is there a reason for this behaviour?

  • 1
    Hi, see this question also. Float comparison behaves differently than integer comparison https://stackoverflow.com/questions/3832592/test-for-floating-point-equality-fe-floating-point-equality – Spyros K Jun 29 '20 at 09:04
  • *"Is there a reason for this behaviour?"* Yes. – Andreas Jun 29 '20 at 09:12
  • Floating point numbers are basically integers with a built-in scaling factor (which is also an integer), plus some other fluff (for instance, they need to be able to values such as NaN and infinity). So they are only approximate at best. When you push them to their limits, the inaccuracy shows. – NomadMaker Jun 29 '20 at 10:02

1 Answers1

0

can use BigDecimal

        BigDecimal decimal1=BigDecimal.valueOf(1.744);
        BigDecimal decimal2=BigDecimal.valueOf(1.745);
        BigDecimal result=decimal2.subtract(decimal1);
        double diff=Math.abs(result.doubleValue());
melody zhou
  • 148
  • 4