-1

What result will I get if from 2.49 I take 0.17 ? 2.32 of course !!! But why the Java return 2.3200000000000003 ?

This is my easy code:

    double x = 2.49;
    double y = 0.17;

    System.out.println(x - y);

How can I get the right result ?

olexiy86
  • 98
  • 1
  • 11
  • I think this duplicate is a better fit: https://stackoverflow.com/questions/322749/retain-precision-with-double-in-java – PM 77-1 Mar 01 '18 at 16:13
  • Take a look [here](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – sjw Mar 01 '18 at 16:14
  • And also [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – 001 Mar 01 '18 at 16:14
  • Found this other duplicate https://stackoverflow.com/questions/6713673/precision-error-with-floats-in-java – pdem Mar 01 '18 at 16:16

1 Answers1

1

You can use this :

  double d = x-y;
  DecimalFormat f = new DecimalFormat("##.00");
  System.out.println(f.format(d));
Léo R.
  • 2,620
  • 1
  • 10
  • 22