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.
maerics :
Try Math.rint(double) or Math.round(double). Regardless of performance differences it's at least more clear and concise.\n\n[Edit]\n\nIn 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:\n\npublic static double integerPart(double d) {\n return (d <= 0) ? Math.ceil(d) : Math.floor(d);\n}\nintegerPart(522.99); // => 522d\nintegerPart(-3.19); // => -3d\n\n\nOf course, this form is likely no faster than casting since it's using a comparison and a method call.",
2011-12-01T14:10:41
AlexR :
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: \n\ndouble d = a*b/c; exactly the same as double d = (double)(long)a*b/c;\n\nYou actually never need to perform casting when moving from lower to upper types. It is correct for primitives (e.g. int -> double) and for classes (e.g. ArrayList -> List).",
2011-12-01T14:10:20