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

JavaRounding

Java Problem Overview


I need to round a number to nearest multiple of 5 (either up or down). For example, here are the list of numbers and the number next to it that it needs to round up/down to.

12.5  10
62.1  60
68.3  70
74.5  75
80.7  80

Numbers will only be positive.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

How about something like this:

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

In case you have an integer as input, otherwise the accepted answer will round it to down.

int value = 37;
value = (int) ( Math.round( value / 5.0 ) * 5.0 );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohannView Question on Stackoverflow
Solution 1 - JavagefeiView Answer on Stackoverflow
Solution 2 - JavaRajesh SampathView Answer on Stackoverflow
Solution 3 - JavaAchintya JhaView Answer on Stackoverflow
Solution 4 - JavakoljaTMView Answer on Stackoverflow
Solution 5 - JavaMáté PintérView Answer on Stackoverflow
Solution 6 - Javauser10073385View Answer on Stackoverflow
Solution 7 - JavaAntonView Answer on Stackoverflow