我正在寻找一种方法,可以轻松地将我的数字格式化成字符串,从看上去像21309809的基本数字到更易读的,比如2,130万,四舍五入来纠正小数。
我试图找到一种方法,用逗号(999,999)格式化数千,用一个小数点(9.9 M)格式化数百万,用小数点(9.9 B)格式化数十亿。
例如,在我的减价文件中,有多个实例需要根据某些公式在文本中实现自动执行。现在,Today, there were `r sum_value` new figures以Today, there were 21309809 new figures的形式返回,但我希望它自动显示为Today, there were 21.3 M new figures,并且当数字下降到阈值或低于阈值时也会自动调整。
发布于 2021-12-23 12:46:45
您可以创建自定义数字格式函数。下面是我在脚本开始时使用的一个。
# Create your function
custom_number_format <- function(x){ifelse(x > 999999999,
paste(format(round((x/1000000000), 2),
nsmall=1, big.mark=","), "B"),
ifelse(x > 999999,
paste(format(round((x/1000000), 1),
nsmall=1, big.mark=","),"M"),
format(round(x), nsmall=0, big.mark=",")))}
# Now try it out
custom_number_format(999)
custom_number_format(999999)
custom_number_format(1000000)
custom_number_format(999900000)
custom_number_format(1000000000)然后,您可以在整个标记文件中加入那个custom_number_format,它将返回正确的结果。
https://stackoverflow.com/questions/70462295
复制相似问题