3

What is the easiest way to round up x so that it is divisible by m ?


For example,

if x = 114, m =4, then the round up should be 116 

or

if x = 119, m=5, then the round up should be 120 
user353gre3
  • 2,747
  • 4
  • 24
  • 27
Adrien
  • 151
  • 1
  • 8

3 Answers3

5
roundUp <- function(x,m) m*ceiling(x / m)
roundUp(119,5)
roundUp(114,4)
Shambho
  • 3,250
  • 1
  • 24
  • 37
2

Divide the number by the require multiple, round the result to the next integer and multiply again by the required multiple.

E.g.: 116 / 5 = 23.1, round to 24, 24 ยท 5 = 120

Maarten Winkels
  • 2,407
  • 16
  • 15
2

Use modulo (%%):

roundUP <- function(x, m){x + m - x %% m}

roundUP(114, 4)
[1] 116
roundUP(119, 5)
[1] 120
roundUP(118, 5)
[1] 120
roundUP(113, 5)
[1] 115
nnn
  • 4,985
  • 4
  • 24
  • 34