How to format a number with a given level of accuracy?

I would like to create a function that returns a vector of numbers whose accuracy is determined by the presence of only n significant digits, but without trailing zeros, and not in scientific notation

for example i would like

somenumbers <- c(0.000001234567, 1234567.89)
myformat(x = somenumbers, n = 3)

for return

[1] 0.00000123  1230000

I played with format, formatCand sprintf, but they don't seem to work independently of each other, and return numbers as character strings (in quotation marks).

This is the closest I got an example:

> format(signif(somenumbers,4), scientific=FALSE)
[1] "      0.000001235" "1235000.000000000"
+5
source share
3 answers

You can use the signif function to round to a given number of significant digits. If you do not need additional trailing 0, then do not "print" the results, but do something else with them.

> somenumbers <- c(0.000001234567, 1234567.89) 
> options(scipen=5)
> cat(signif(somenumbers,3),'\n')
0.00000123 1230000 
> 
+7

sprintf, , :

sprintf(c("%1.8f", "%1.0f"), signif(somenumbers, 3))
[1] "0.00000123" "1230000"
+5

myformat <- function(x, n) {
    noquote(sapply(a,function(x) format(signif(x,2), scientific=FALSE)))
}
+1
source

All Articles