Rounding Down to nearest whole number - am I cheating or is this more than adequate?

There is already a function to do that. It's called floor:

double d = Math.floor(2.9999) //result: 2.0

Even simpler and potential faster

double d = 2.99999999;
long l = (long) d; // truncate to a whole number.

This will round towards 0. Math.floor() rounds towards negative infinity. Math.round(x - 0.5) also rounds towards negative infinity.


Everyone always wants to use fancy functions, but forgets about the humble modulus. My solution:

number = x-(x%1);

subtracts the remainder of division by one, so x = 2.999 will = 2, 3.111 will = 3 and so on. The cool thing about this is that you can round down the multiple of anything just by changing that 1 into whatever you like.

Tags:

Java