[R] Rounding problem R vs Excel

Hedderik van Rijn hedderik at cmu.edu
Tue Jun 3 02:50:20 CEST 2003


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.




More information about the R-help mailing list