Round up from .5

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, digits) {
  posneg = sign(x)
  z = abs(x)*10^digits
  z = z + 0.5 + sqrt(.Machine$double.eps)
  z = trunc(z)
  z = z/10^digits
  z*posneg
}

x is the object you want to round, and digits 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).)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)