325

我有一个数字,例如 1.128347132904321674821,我想在输出到屏幕(或写入文件)时仅显示两位小数。如何做到这一点?

x <- 1.128347132904321674821

编辑:

指某东西的用途:

options(digits=2)

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

--

答案:round(x, digits=2)

4

14 回答 14

462

背景:此页面上建议的一些答案(例如 , signifoptions(digits=...)不保证显示任意数字的特定小数位数。我认为这是 R 中的一个设计特征,良好的科学实践涉及基于“有效数字”原则显示一定数量的数字。然而,在许多领域(例如,APA 风格、业务报告)中,格式要求要求显示一定数量的小数位。这通常是为了一致性和标准化目的,而不是关注重要数字。

解决方案

下面的代码正好显示了数字的两位小数x

format(round(x, 2), nsmall = 2)

例如:

format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"

一个更通用的函数如下,其中x是数字,k是要显示的小数位数。trimws删除任何前导空格,如果您有数字向量,这可能很有用。

specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))

例如,

specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"

替代方案的讨论:

formatC答案sprintf 答案工作得相当好。但在某些情况下,它们会显示负零,这可能是不需要的。IE,

formatC(c(-0.001), digits = 2, format = "f")
# [1] "-0.00"
sprintf(-0.001, fmt = '%#.2f')
# [1] "-0.00"

一种可能的解决方法如下:

formatC(as.numeric(as.character(round(-.001, 2))), digits = 2, format = "f")
# [1] "0.00" 
于 2012-08-27T00:43:11.267 回答
47

您可以根据需要格式化一个数字,例如x,精确到小数位。这x是一个有很多小数位的数字。假设我们希望显示此数字的小数点后 8 位:

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

这里format="f"给出通常小数位的浮点数,例如 xxx.xxx,并digits指定位数。相比之下,如果你想获得一个整数来显示你会使用format="d"(很像sprintf)。

于 2016-03-16T11:36:58.610 回答
34

你可以试试我的包formattable

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> x <- formattable(1.128347132904321674821, digits = 2, format = "f")
> x
[1] 1.13

好消息是,x它仍然是一个数字向量,您可以使用相同的格式进行更多计算。

> x + 1
[1] 2.13

更好的是,数字不会丢失,您可以随时重新格式化更多数字:)

> formattable(x, digits = 6, format = "f")
[1] 1.128347
于 2015-05-29T08:09:04.853 回答
32

假设您要保留尾随零,则保留 2 个小数位

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

这使

[1] "5.50"

正如@mpag 下面提到的那样,R 似乎有时可以通过 this 和 round 方法给出意想不到的值,例如 sprintf(5.5550, fmt='%#.2f') 给出 5.55,而不是 5.56

于 2018-01-15T14:53:29.673 回答
11

如果您更喜欢有效数字而不是固定数字,那么signif命令可能很有用:

> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300
于 2010-08-09T20:31:40.967 回答
10

类似的东西:

options(digits=2)

数字选项的定义:

digits: controls the number of digits to print when printing numeric values.
于 2010-08-09T20:04:28.880 回答
9

检查函数prettyNum、格式

有试用零(例如 123.1240)使用sprintf(x, fmt='%#.4g')

于 2010-08-09T20:04:49.780 回答
6

The function formatC() can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.

于 2013-04-26T21:13:16.183 回答
4

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

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)
于 2014-04-14T03:30:07.377 回答
3

请注意,R 中的数字对象以double precision存储,这为您提供(大约)16 位十进制数字的精度 - 其余的将是噪音。我承认上面显示的数字可能只是一个示例,但它是 22 位长。

于 2010-08-10T05:01:06.143 回答
2

在我看来,会是这样的

library(tutoR)
format(1.128347132904321674821, 2)

每一点在线帮助

于 2010-08-09T20:02:17.970 回答
1

如果您只想对数字或列表进行四舍五入,只需使用

round(data, 2)

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

于 2018-07-05T04:04:46.080 回答
0

这是我从单位到数百万的方法。数字参数让我调整有效值的最小数量(整数+小数)。您可以先在内部调整小数舍入。

number <-function(number){
  result <- if_else(
    abs(number) < 1000000,
    format(
      number, digits = 3,
      big.mark = ".",
      decimal.mark = ","
    ),
    paste0(
      format(
        number/1000000,
        digits = 3,
        drop0trailing = TRUE,
        big.mark = ".",
        decimal.mark = ","
      ),
      "MM"
    )
  )
  # result <- paste0("$", result)
  return(result)
}
于 2020-11-27T17:21:40.000 回答
0

我编写了这个可以改进的函数,但看起来在极端情况下效果很好。例如,在 0.9995 的情况下,投票正确答案给我们 1.00,这是不正确的。在数字没有小数的情况下,我使用该解决方案。

round_correct <- function(x, digits, chars = TRUE) {
  if(grepl(x = x, pattern = "\\.")) {
    y <- as.character(x)
    pos <- grep(unlist(strsplit(x = y, split = "")), pattern = "\\.", value = FALSE)
    if(chars) {
      return(substr(x = x, start = 1, stop = pos + digits))
    }
    return(
      as.numeric(substr(x = x, start = 1, stop = pos + digits))
    )
  } else {
    return(
      format(round(x, 2), nsmall = 2)
    )
  }
}

例子:

round_correct(10.59648, digits = 2)
[1] "10.59"
round_correct(0.9995, digits = 2)
[1] "0.99"
round_correct(10, digits = 2)
[1] "10.00"
于 2021-04-08T02:17:17.153 回答