8

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
just eric
  • 927
  • 1
  • 11
  • 23

1 Answers1

21

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

double mRound(double value, double factor) {
    return Math.round(value / factor) * factor;
}
Ry-
  • 218,210
  • 55
  • 464
  • 476