Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers to specific multiples [duplicate]

How can I round to a specific multiple in Java? In excel there is the mround function which allows for easy rounding to a specified multiple like so:

    mRound(variable,multiple)

so mRound(x,3) would return 9 if x = 7.9 and 6 if x = 7.2.

All of the rounding functions I have found so far always round to the nearest whole number or to a specified number of decimal places but I want to be able to change the multiple for each variable. Does anyone know what function would be best for this situation?

like image 411
just eric Avatar asked May 04 '12 21:05

just eric


People also ask

How do you round up multiples?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.

Which function rounds a number to the nearest specified multiple?

To round a number to a specific multiple (for example, to round to the nearest 0.5), use the MROUND function.

How do you round up 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.

How do you round to a specific number in Excel?

To round up to the nearest specified place, use the ROUNDUP function. To round up to the nearest specified multiple, use the CEILING function. To round down and return an integer only, use the INT function. To truncate decimal places, use the TRUNC function.


1 Answers

Just divide by the number, round, and multiply by the number.

double mRound(double value, double factor) {
    return Math.round(value / factor) * factor;
}
like image 154
Ry- Avatar answered Sep 18 '22 20:09

Ry-