Take the 2-minute tour ×

Now, there has been some very similar questions on SO about rounding and significance, but non solves my issue. Here it is:

How to round randomly occurring numbers like these:

data <- c(152.335, 39.431, 21.894)

I would like to have them rounded like this:


I have tried:

print(formatC(signif(data,digits=2), digits=2,format="f"))


[1] "150.00" "39.00"  "22.00"

The above command requires me to change the digits= to 1 or 2 in order to obtain the desired outcome. But, I would like a global - fit for all command. Thanks.

share|improve this question
SO 21.8 turns 20? this doesnt make sense. –  Fernando Aug 28 '13 at 16:01
Duplicate? stackoverflow.com/questions/6461209/… –  Henrik Aug 28 '13 at 16:04
@Fernando, it seems like Max wishes to round to nearest 10. –  Henrik Aug 28 '13 at 16:05
@Henrik: Yes thanks. This is it. Actually the plyr package does what I need. Thats: round_any(data, 5) –  Max Aug 28 '13 at 16:08
@Max, may I suggest that you make your title more specific, in the sense that you wish to round to nearest 10, and more general in the sense that your question probably applies also to numbers other than random numbers. This makes it easier for other to find answers when they search on SO. –  Henrik Aug 28 '13 at 16:14
add comment

2 Answers

up vote 7 down vote accepted

From ?round

Rounding to a negative number of digits means rounding to a power of ten, so for example ‘round(x, digits = -2)’ rounds to the nearest hundred.


data <- c(152.335, 39.431, 21.894)
round(data, -1)
#[1] 150  40  20
share|improve this answer
Your simple solution works marvellous. Thanks. –  Max Aug 28 '13 at 16:19
add comment

You actually want a different argument for signif here. This seems to do the trick -- 2 digits for first argument, one for the last two:

R> dat <- c(152.335, 39.431, 21.894)
R> dat
[1] 152.335  39.431  21.894
R> signif(dat, digits=c(2,1,1))
[1] 150  40  20

You can possibly generalize this via something like

R> signif(dat, digits=floor(log10(dat)))
[1] 150  40  20
share|improve this answer
Thanks. Actually just found out (as Henrik pointed out), the plyr package command: round_any(data, 5) ,does what I need. But your solution is from R basic and hence no package required! –  Max Aug 28 '13 at 16:11
add comment

Your Answer


