Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Math.round return a long but Math.floor return a double?

Tags:

java

math

Why the inconsistency?

like image 220
Leo Jay Avatar asked Aug 05 '10 07:08

Leo Jay


1 Answers

There is no inconsistency: the methods are simply designed to follow different specifications.

  • long round(double a)
    • Returns the closest long to the argument.
  • double floor(double a)
    • 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.
    • Compare with double ceil(double a)
  • double rint(double a)
    • Returns the double value that is closest in value to the argument and is equal to a mathematical integer

So by design round rounds to a long and rint rounds to a double. This has always been the case since JDK 1.0.

Other methods were added in JDK 1.2 (e.g. toRadians, toDegrees); others were added in 1.5 (e.g. log10, ulp, signum, etc), and yet some more were added in 1.6 (e.g. copySign, getExponent, nextUp, etc) (look for the Since: metadata in the documentation); but round and rint have always had each other the way they are now since the beginning.

Arguably, perhaps instead of long round and double rint, it'd be more "consistent" to name them double round and long rlong, but this is argumentative. That said, if you insist on categorically calling this an "inconsistency", then the reason may be as unsatisfying as "because it's inevitable".

Here's a quote from Effective Java 2nd Edition, Item 40: Design method signatures carefully:

When in doubt, look to the Java library APIs for guidance. While there are plenty of inconsistencies -- inevitable, given the size and scope of these libraries -- there are also fair amount of consensus.

Distantly related questions

  • Why does int num = Integer.getInteger("123") throw NullPointerException?
  • Most awkward/misleading method in Java Base API ?
  • Most Astonishing Violation of the Principle of Least Astonishment
like image 55
polygenelubricants Avatar answered Oct 02 '22 14:10

polygenelubricants