When i call the getWeight method with the 96 argument, then the output will be 16.32.
It's OK.
But if i call the getWeight method for example with the 95 argument, then the output will be 16.150000000000002 instead of 16.15.
I wonder why?...
(And the Verify button ticks all the boxes with green.)
I used the ' return earthWeight*0.17; ' statement.
In some cases why the result is _.150000000000002 instead of _.15?
Resolved
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
29 January 2020, 21:42
It is because computers do math in binary, which is imprecise with the floating point decimal system.
Here is website that explains this simply:
https://floating-point-gui.de/basic/
or you can read this masters thesis on the problem if simple isnt good enough for you:
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
0
Gellert Varga
29 January 2020, 23:09
Thank you very much!!:)
But now i have a new question about it...
From the first link: "If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it." -- How can i do this?
0
Guadalupe Gagnon
30 January 2020, 00:01
If you only are concerned about display, then String.format() can help you.
If you want the actual value held in the variable to be rounded to a certain amount, then Math.round() can help you.
You can google either of these methods for tuturials on how to use them. Both can be any number of plaves after the decimal.
0
Gellert Varga
30 January 2020, 20:56
Thank you!
I was google this topic, and finally the follows was helped to me:
System.out.printf("Value with 2 digits after decimal point= %.2f %n", getWeight(95));
It works!
+1