Why does Math.round(double)
return long
while Math.floor(double)
return double
? Is there a technical reason or is it just a historical aberration?
Asked
Active
Viewed 97 times
1

DodgyCodeException
- 5,963
- 3
- 21
- 42
-
Same could be said of floor: "Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer." – Koekje Jan 19 '18 at 12:19
1 Answers
2
Math.round
is not an opposite of Math.floor
; Math.ceil
is.
The two opposite methods, floor
and ceil
(short for "ceiling"), are for producing double
s with their fraction part removed. They are consistent with each other at returning a double
.
round
, on the other hand, is for converting from double
to long
by rounding the number.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
1It is also worth to note that both methods preserve some specialties from `double`, like NaN, infinity or positive and negative zero and returns the argument in these cases. – Tom Jan 19 '18 at 12:40
-
Thanks for the ideas stated here. I wasn't implying round was the opposite of floor; I could have worded the question "Why does Math.round(double) return long while Math.floor(double) and Math.ceil(double) return double?" but left out the second method for brevity. I've just found a duplicate question (with the kind of answers I was looking for) so I've marked my question as a duplicate. The answer, of course, was that I had forgotten about the method `double rint(double)` which does, in fact, go with floor and ceil consistently. – DodgyCodeException Jan 19 '18 at 14:10