Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up double to long in Java [duplicate]

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?

like image 252
MukeshKoshyM Avatar asked Jun 03 '26 18:06

MukeshKoshyM


2 Answers

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).

like image 108
Kevin W. Avatar answered Jun 05 '26 09:06

Kevin W.


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.

like image 24
Durandal Avatar answered Jun 05 '26 09:06

Durandal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!