Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different rounding rule based on number of digits before the decimal

Tags:

rounding

r

digits

Say we have the following numerical vector:

y=c(0.111,1.11,11.1,111.1)

I would like it to be rounded as follows:

0.11,1.11,11.1,111  

This rule is simple: I want three digits in total! But if the number is large (e.g. 1111 or 11111) then keep all digits, but without any decimals.

Surely, there has to be a simpler solution?:

lapply(y,function(x){
  ifelse(nchar(as.integer(x))<1,round(x,digits=3),
         ifelse(nchar(as.integer(x))==1,round(x,digits=2),
                ifelse(nchar(as.integer(x))==2,round(x,digits=1),
                       ifelse(nchar(as.integer(x))>2,round(x,digits=0)
                       ))))
}
)
like image 738
user2862862 Avatar asked Dec 17 '22 14:12

user2862862


1 Answers

Just use signif:

y <- c(0.111,1.11,11.1,111.1,1111)
signif(y, pmax(3,trunc(log10(y)+1)))
#[1]    0.111    1.110   11.100  111.000 1111.000

The pmax(...) part accounts for the case in which the number has 4 or more digits before the decimal (log10 is just a way to count those digits).

like image 180
nicola Avatar answered May 10 '23 18:05

nicola