1

double x= 2.2,y=2.13;

How can i do do operations like x+y or x-y * x/y? For example x-y should be 0.07 but java gives me 0.07000000000000028

f1sh
  • 11,489
  • 3
  • 25
  • 51
  • 3
    You did the operation correctly. But there's limits on how precise a double can be saved internatlly. Use BigDecimal instead. – f1sh Aug 26 '19 at 12:28
  • 2
    0.07 can not be exactly represented by a floating point number. https://en.wikipedia.org/wiki/IEEE_754 – Jim Nilsson Aug 26 '19 at 12:28
  • DecimalFormat df = new DecimalFormat("#.##"); System.out.print(df.format(x)); It will simply cut your result but it will not affect the calculation itself it will be still with the double precision. –  Aug 26 '19 at 12:29

1 Answers1

-4

You can use Math.round() function.

import java.lang.Math;
System.out.println(Math.round(x-y));
AzamAbbasi
  • 91
  • 1
  • 9
  • Why do you think this helps in this case? What do you think `Math.round(0.07000000000000028)` returns? – f1sh Aug 26 '19 at 12:37
  • As i understand that you need a simply precised result for a double precision. so Math.round will work and return you 0.07 – AzamAbbasi Aug 26 '19 at 12:48
  • 1
    You understand incorrectly. The javadoc says: "Returns the closest long to the argument, with ties rounding to positive infinity.". So the result will actually be an integer ... zero. – Stephen C Aug 26 '19 at 12:54
  • @AzamAbbasi why 0.07? Why not 0.0700000000000003? Why not 0.1? – f1sh Aug 26 '19 at 16:52
  • I agree with @Stephen C – AzamAbbasi Aug 27 '19 at 07:48