Round up from .5

jakob-r picture jakob-r · Oct 2, 2012 · Viewed 31k times · Source

Yes I know why we always round to the nearest even number if we are in the exact middle (i.e. 2.5 becomes 2) of two numbers. But when I want to evaluate data for some people they don't want this behaviour. What is the simplest method to get this:

x <- seq(0.5,9.5,by=1)
round(x)

to be 1,2,3,...,10 and not 0,2,2,4,4,...,10.

Edit: To clearify: 1.4999 should be 1 after rounding. (I thought this would be obvious)

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Oct 2, 2012

This is not my own function, and unfortunately, I can't find where I got it at the moment (originally found as an anonymous comment at the Statistically Significant blog), but it should help with what you need.

round2 = function(x, n) {
  posneg = sign(x)
  z = abs(x)*10^n
  z = z + 0.5 + sqrt(.Machine$double.eps)
  z = trunc(z)
  z = z/10^n
  z*posneg
}

x is the object you want to round, and n is the number of digits you are rounding to.

An Example

x = c(1.85, 1.54, 1.65, 1.85, 1.84)
round(x, 1)
# [1] 1.8 1.5 1.6 1.8 1.8
round2(x, 1)
# [1] 1.9 1.5 1.7 1.9 1.8

(Thanks @Gregor for the addition of + sqrt(.Machine$double.eps).)