0

when use Java NetBeans

double purchase = 19.93;
double payment = 20.00;
double change = payment - purchase;
System.out.println(change);

the result is : 0.07000000000000028 when I use Math.round method I got result "0" zero! I don't want zero I want 0.07 but when I do multiply by 100 then divide by 100 I got 0.07 easily!!!

double round = Math.round(change * 100.0) / 100.0; 
System.out.println(rounded);

Result : 0.07!!

what is the reasons behind that? I'm beginner in java pls answer me as beginner

skomisa
  • 16,436
  • 7
  • 61
  • 102
  • [1] The [javadoc for Math.round(double)](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Math.html#round(double)) explains what you are seeing: _"Returns the closest long to the argument..."_. [2] Also, I modified your tags since this question is about [java], but not really about [netbeans] or [numbers]. – skomisa Jan 27 '22 at 03:48
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Mad Physicist Jan 27 '22 at 03:55
  • @skomisa then why when I do Math.round(change * 100.0) / 100.0; everything goes ok? when I multiply by 100 then divide? I'm beginner can u explain to me please – Hannibal lecter Jan 27 '22 at 20:39
  • This is just a simple maths problem: `0.07000000000000028 * 100 = 7.000000000000028`, rounding that to the nearest number yields `7`, `7 / 100 = 0.07`. – Henry Twist Jan 31 '22 at 14:53

0 Answers0