3

Is there a method in java which round up double to Long in java?

eg. double d=2394867326.23; I need to round this up to 2394867327. The result is not an integer, so I think cannot use Math.ceil.

Do we have a method in java which return the Long instead of int?

MukeshKoshyM
  • 514
  • 1
  • 8
  • 16

2 Answers2

8

Math.ceil returns a double according to this, so you should just be able to cast it to a long after calling math.ceil(double).

Kevin W.
  • 1,143
  • 10
  • 15
1

You could rely on the property that a cast to long will always truncate:

public static long d2lCeil(double d) {
    long l = (long) d;
    return d == l ? l : l + 1;
}

The trick this method is using is that in the cast to long any fraction will be simply lost. The presence of a fraction is then detected by comparing the long and double, if they're not the same there must be a fraction, thus the long needs to be rounded up.

Durandal
  • 19,919
  • 4
  • 36
  • 70