views:

318

answers:

2

Are there any drawbacks to this code, which appears to be a faster (and correct) version of java.lang.Math.round?

public static long round(double d) {

    if (d > 0) {
        return (long) (d + 0.5d);
    } else {
        return (long) (d - 0.5d);
    }
}

It takes advantage of the fact that, in Java, truncating to long rounds in to zero.

+5  A: 

Yes; you're not accounting for underflow or overflow. Pragmatically speaking, this may not matter for your application.

Jonathan Feinberg
+10  A: 

There are some special cases which the built in method handles, which your code does not handle. From the documentation:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
Kristian