使用逗号千位分隔符和指定的小数格式化 R 中的数字 [英] Format number in R with both comma thousands separator and specified decimals
本文介绍了使用逗号千位分隔符和指定的小数格式化 R 中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用千位分隔符格式化数字并指定小数位数.我知道如何分开做这些,但不能一起做.
I'd like to format numbers with both thousands separator and specifying the number of decimals. I know how to do these separately, but not together.
例如,我使用 format
每 this 作为小数:
For example, I use format
per this for the decimals:
FormatDecimal <- function(x, k) {
return(format(round(as.numeric(x), k), nsmall=k))
}
FormatDecimal(1000.64, 1) # 1000.6
对于千位分隔符,formatC
:
formatC(1000.64, big.mark=",") # 1,001
但这些并不能很好地结合在一起:
These don't play nicely together though:
formatC(FormatDecimal(1000.64, 1), big.mark=",")
# 1000.6, since no longer numeric
formatC(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",")
# Error: unused argument (nsmall=1)
如何获得1,000.6
?
这不同于 这个问题它询问将 3.14 格式化为 3,14(被标记为可能的 dup).
This differs from this question which asks about formatting 3.14 as 3,14 (was flagged as possible dup).
推荐答案
format
not formatC
:
format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",") # 1,000.6
这篇关于使用逗号千位分隔符和指定的小数格式化 R 中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文