Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trailing zeros after sequential rounding with round() followed by signif()

I am trying to apply a sequential rounding function on any real number so that the following condition is met: "Numbers should be reported with no more than two decimal digits and no more than two significant figures".

For example:
0.0236 should be reported as 0.02
0.236 should be reported as 0.24
2.36 should be reported as 2.4
23.6 should be reported as 24
236 should be reported as 240

It seems that whenever there are trailing zeros after rounding with round and signif, these are omitted (e.g. 0.90023 becomes 0.9 instead of 0.90). I have tried the following piece of code:

    my_round <- function(x1) {
            x2 <- formatC(x1, digits=2, format="f", drop0trailing=FALSE)
            x2 <- as.numeric(x2)
            x3 <- formatC(x2, digits=2, format="fg", flag="#", drop0trailing=FALSE)
            x3 <- as.numeric(x3)
            print(x3)
    }

This works fine for any number except those like 195 (more than two significant figures in their integer part) which remains 195 instead of getting rounded to 200.

I would appreciate any help provided on this topic.
(R v3.1.0, 2014-04-10)

like image 597
user3806114 Avatar asked Nov 27 '25 09:11

user3806114


1 Answers

You can combine the function sprintf and the ideas discussed here.

ceil.ten <- function(x) 
  if (x > 100) ceiling(x/10)*10 else x

sprintf("%.2f", ceil.ten(0.0236))
# [1] "0.02"
sprintf("%.2f", ceil.ten(0.236))
# [1] "0.24"
sprintf("%.2f", ceil.ten(2.36))
# [1] "2.36"
sprintf("%.2f", ceil.ten(23.6))
# [1] "23.60"
sprintf("%.2f", ceil.ten(236))
# [1] "240.00"
sprintf("%.2f", ceil.ten(195))
# [1] "200.00"
like image 191
javlacalle Avatar answered Nov 29 '25 22:11

javlacalle