如何格式化具有指定级别的精度的数字? [英] How to format a number with specified level of precision?

查看:140
本文介绍了如何格式化具有指定级别的精度的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,它返回一个只有 n 的有效数字反映的精度的数字,但不能以零的形式出现,而不是以科学的方式表示

例如,我想要

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

返回

  [1] 0.00000123 1230000 

我一直在玩格式 formatC sprintf ,但他们似乎并不想单独处理每个数字,他们返回的数字作为字符串(引号)。

这是最接近的,我已经得到例子:

 >格式(signif(somenumbers,4),scientific = FALSE)
[1]0.0000012351235000.000000000


 > ; somenumbers<  -  c(0.000001234567,1234567.89)
>选项(scipen = 5)
>猫(signif(somenumbers,3),'\\\
')
0.00000123 1230000
>


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 
> 

这篇关于如何格式化具有指定级别的精度的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆