[R] Rounding

Daniel Mastropietro mastropi at uwalumni.com
Thu Sep 19 15:41:56 CEST 2002


You could find the number of digits by doing a while loop:

ndigits <- function(x)
{
         n <- 0;
         rounding <- 1;
         while (rounding > 0)
         {
             rounding <- floor(abs(x)/10^n) * 10^n;
             n <- n + 1;
         }
         return(n-1)
}


Daniel Mastropietro

At 09:22 PM 19/9/2002 +1200, Ko-Kang Kevin Wang wrote:
>Hi,
>
>Thanks for the quick solution.
>
>However I'm just wondering what happens if I'd like to generalise it.  For
>example I can do:
>   x <- 459
>   floor(x / 100) * 100
>or
>   ceiling(x / 100) * 100
>
>Now my questions is: how do I work out the number of digits x has?  For
>example in this case I have 3 digits for x (4, 5, and 9), hence I can
>divide it by 100 first, floor() or ceiling() the result, then times 100.
>
>If I have n digits for x, this means I want to divide by (n - 1).
>
>But I'm not sure how to find n :-(

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list