Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up a number to nearest multiple of 5

Tags:

java

rounding

Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can't find this one.

This does it for ten.

double number = Math.round((len + 5)/ 10.0) * 10.0; 
like image 875
Daniel Cook Avatar asked Feb 16 '12 00:02

Daniel Cook


People also ask

How do you round to the nearest multiple?

The MROUND function rounds a number to the nearest given multiple. The multiple to use for rounding is provided as the significance argument. If the number is already an exact multiple, no rounding occurs and the original number is returned. You can...

How do you round up or down 5?

Here's the general rule for rounding: If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.

How do you round to the nearest 5 in decimals?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.


2 Answers

To round to the nearest of any value

int round(double i, int v){     return Math.round(i/v) * v; } 

You can also replace Math.round() with either Math.floor() or Math.ceil() to make it always round down or always round up.

like image 172
Arkia Avatar answered Sep 21 '22 23:09

Arkia


int roundUp(int n) {     return (n + 4) / 5 * 5; } 

Note - YankeeWhiskey's answer is rounding to the closest multiple, this is rounding up. Needs a modification if you need it to work for negative numbers. Note that integer division followed by integer multiplication of the same number is the way to round down.

like image 42
Tim Cooper Avatar answered Sep 20 '22 23:09

Tim Cooper