+ 2

Division and rounding/truncation error Java

https://code.sololearn.com/cqS3ftwVDuy6/?ref=app I was looking at the difference between double and floats and then noticed something else a bit strange. 31 / 7 = 4.4.... but the output shown is 4.0 What's wrong with my code? Also, if I want it to round up: 4.4 = 5, shouldn't Math.ceil do that?

29th Dec 2021, 10:21 PM
Ausgrindtube
Ausgrindtube - avatar
2 Answers
+ 5
When you divide an integer by an integer in java the result is an integer. Assigning the result to float or double does not change the result of the calculation. It merely coverts it. So you have to convert at least one of the numbers *before* doing division.
29th Dec 2021, 10:33 PM
Simon Sauter
Simon Sauter - avatar
+ 3
Oh facepalm! I'll update it and check. **edit** Yep! That's done it! Thanks Simon Sauter
30th Dec 2021, 8:07 AM
Ausgrindtube
Ausgrindtube - avatar