Skip to content
Prev 32804 / 398506 Next

Rounding problem R vs Excel

Does this script do what you want?

cround <- function(x,digits=0) {
   a <- ifelse(x>0,.5,-.5)
   if (digits==0) {
     floor(x+a)
   } else {
     m <- 10^digits
     floor(x*m+a)/m
   }
}

 > cround(1.4535,1)
[1] 1.5
 > cround(1.4535,2)
[1] 1.45
 > cround(1.4535,3)
[1] 1.454
 > cround(1.4535,4)
[1] 1.4535


   - Hedderik.