我有一个数字,例如1.128347132904321674821,我想在输出到屏幕(或写入到文件)时仅显示两个小数点后的位置。要怎么做呢?

x <- 1.128347132904321674821

编辑:

用途:

options(digits=2)

被认为是一个可能的答案。是否有一种方法可以在脚本中指定这一点,以便一次性使用?当我将它添加到我的脚本时,它似乎没有做任何不同的事情,我对大量重新输入来格式化每个数字不感兴趣(我正在自动化一个非常大的报告)。

--

答案:整数(x,数字=2)


当前回答

我使用这个变体来强制打印K位小数点后数位:

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)

其他回答

你可以格式化一个数字,比如x,直到你想要的小数点。这里x是一个小数点后很多位的数。假设我们希望显示这个数字的小数点后8位:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

这里format="f"给出的是小数点后的浮点数,比如xxx。Xxx, digits表示数字位数。相比之下,如果你想要显示一个整数,你可以使用format="d"(很像sprintf)。

小数点后两位假设你想保持后面的0

sprintf(5.5, fmt = '%#.2f')

这给了

[1] "5.50"

正如下面@mpag提到的,似乎R有时会给出意想不到的值,而舍入方法,例如sprintf(5.5550, fmt='%#.2f')给出5.55,而不是5.56

就像这样:

options(digits=2)

数字选项的定义:

digits: controls the number of digits to print when printing numeric values.
library(dplyr)
# round the numbers
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, 2), nsmall = 2)}))

在这里,我将所有数值更改为只有2位小数。如果你需要把它改到小数点后几位

# round the numbers for k decimal places
df <- df %>%
  mutate(across(where(is.numeric), .fns = function(x) {format(round(x, k), nsmall = k)}))

将k替换为所需的小数点后数位

如果你只是想四舍五入一个数字或一个列表,只需使用

round(data, 2)

然后,数据将四舍五入到小数点后2位。