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?
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.
To round a number to a specific multiple (for example, to round to the nearest 0.5), use the MROUND function.
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.
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.
Just divide by the number, round, and multiply by the number.
double mRound(double value, double factor) {
return Math.round(value / factor) * factor;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With