Background: Some answers suggested on this page (e.g., signif, options(digits=...)) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.
解决方案:
下面的代码显示了数字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答案工作得相当好。但在某些情况下,它们会显示负0,这可能是不需要的。也就是说,
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"