How to format a number with specified level of precision?

元气小坏坏 提交于 2019-12-10 14:22:38

问题


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"

回答1:


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 
> 



回答2:


sprintf seems to do it:

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



回答3:


how about

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


来源:https://stackoverflow.com/questions/5225920/how-to-format-a-number-with-specified-level-of-precision

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!