Rounding numbers

Problem

You want to round numbers.

Solution

There are many ways of rounding: to the nearest integer, up, down, or toward zero.

  1. x <- seq(-2.5, 2.5, by=.5)
  2. # Round to nearest, with .5 values rounded to even number.
  3. round(x)
  4. #> [1] -2 -2 -2 -1 0 0 0 1 2 2 2
  5. # Round up
  6. ceiling(x)
  7. #> [1] -2 -2 -1 -1 0 0 1 1 2 2 3
  8. # Round down
  9. floor(x)
  10. #> [1] -3 -2 -2 -1 -1 0 0 1 1 2 2
  11. # Round toward zero
  12. trunc(x)
  13. #> [1] -2 -2 -1 -1 0 0 0 1 1 2 2

It is also possible to round to other decimal places:

  1. x <- c(.001, .07, 1.2, 44.02, 738, 9927)
  2. # Round to one decimal place
  3. round(x, digits=1)
  4. #> [1] 0.0 0.1 1.2 44.0 738.0 9927.0
  5. # Round to tens place
  6. round(x, digits=-1)
  7. #> [1] 0 0 0 40 740 9930
  8. # Round to nearest 5
  9. round(x/5)*5
  10. #> [1] 0 0 0 45 740 9925
  11. # Round to nearest .02
  12. round(x/.02)*.02
  13. #> [1] 0.00 0.08 1.20 44.02 738.00 9927.00