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
  • 14,478
  • 7
  • 54
  • 90
  • [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

1 Answers1

0

In fact, this is not really Java's fault but it is due to how the hardware handles division with two float numbers. This is quite complicated, so if you are really interested in it, you can read this article.

You can try this workaround to round to two decimal points but yours is apparently working as well.

jmjumper
  • 1
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 31 '22 at 15:03