Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: round to nearest multiple of 5 (either up or down)

Tags:

java

rounding

People also ask

Does Java round .5 up or down?

The answer is Yes. Java does a round down in case of division of two integer numbers.

How do you round up to multiples of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.


haven't tested it, but 5*(Math.round(f/5)); should work


Nearest Multiple of 5 for Upper value

5*(Math.ceil(Math.abs(number/5)));

for Lower Value

5*(Math.floor(Math.abs(number/5)));

it gives Positive value only.


How about something like this:

return round((number/5))*5;

public static void main(String args[]) {
    double num = 67.5;
    if (num % 5 == 0)
        System.out.println("OK");
    else if (num % 5 < 2.5)
        num = num - num % 5;
    else
        num = num + (5 - num % 5);
    System.out.println(num);

}

Try this.


Gefei's solution is working, but I had to convert explicitly to double like this: 5*(Math.round((double)f/5))


There are many other solutions on this page, but I believe this is the most concise one.

To find the closest multiple of x for a given number,

let x be the multiple and num be the given number:

// The closest multiple of x <= num
int multipleOfX = x * ( num / x );

In your case:

int multipleOf5 = 5 * ( num / 5 );