简体   繁体   中英

Java typecasting for retrieving integer part of a double as double

I sometimes tend to use (double)(long)(a*b/c) to store the integer part of the result as double. This works well for negative numbers too.

Is there any better way to achieve the same thing as I believe typecasting is a costly operation.

Please note I'm looking for Integer part of the number and not the rounded value. For eg :

MyObj.setDouble((double)(long)(522.99))
MyObj.getDouble() returns 522.0 and not 523.0

Thanks.

Try Math.rint(double) or Math.round(double) . Regardless of performance differences it's at least more clear and concise.

[Edit]

In response to your clarified question - "how do I get the integer part of a double without casting" (despite your title asking about rounding ), try this:

public static double integerPart(double d) {
  return (d <= 0) ? Math.ceil(d) : Math.floor(d);
}
integerPart(522.99); // => 522d
integerPart(-3.19); // => -3d

Of course, this form is likely no faster than casting since it's using a comparison and a method call.

Performance is not an issue here. But code (double)(long)(a*b/c) is ugly. You actually do not need casting at all if you assign the result to `double variable:

double d = a*b/c; exactly the same as double d = (double)(long)a*b/c;

You actually never need to perform casting when moving from lower to upper types. It is correct for primitives (eg int -> double ) and for classes (eg ArrayList -> List ).

那么Math.floor(double)我看不出整数部分和它之间的区别。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM