开发者

How to format a number with specified level of precision?

I would like to create a function that returns a vector of numbers a precision reflected by having only n significant figures, but without trailing zeros, and not in scientific notation

e.g, I would like

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

to return

[1]开发者_如何学运维 0.00000123  1230000

I have been playing with format, formatC, and sprintf, but they don't seem to want to work on each number independently, and they return the numbers as character strings (in quotes).

This is the closest that i have gotten example:

> format(signif(somenumbers,4), scientific=FALSE)
[1] "      0.000001235" "1235000.000000000"


You can use the signif function to round to a given number of significant digits. If you don't want extra trailing 0's then don't "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 
> 


sprintf seems to do it:

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


how about

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜