如何做出“漂亮的四舍五入”?
我需要进行这样的舍入并将其转换为字符:
as.character(round(5.9999,2))
我希望它成为 6.00
,但它只给我 6
无论如何我可以做到这一点显示6.00
?
I need to do a rounding like this and convert it as a character:
as.character(round(5.9999,2))
I expect it to become 6.00
, but it just gives me 6
Is there anyway that I can make it show 6.00
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试其中之一:
还有
formatC()
和prettyNum()
。Try either one of these:
There are also
formatC()
andprettyNum()
.为了帮助解释发生了什么 -
round(5.9999, 2)
调用将您的数字四舍五入到最接近的百位,这为您提供非常接近的数字(不是字符串)到(或者完全等于,如果你幸运地使用浮点表示)6.00。然后as.character()
查看该数字,最多占用 15 个有效数字(请参阅?as.character
),以便以足够的精度表示它,并且确定只需要 1 位有效数字。这就是你得到的。To help explain what's going on - the
round(5.9999, 2)
call is rounding your number to the nearest hundredths place, which gives you the number (not string) very close to (or exactly equal to, if you get lucky with floating-point representations) 6.00. Thenas.character()
looks at that number, takes up to 15 significant digits of it (see?as.character
) in order to represent it to sufficient accuracy, and determines that only 1 significant digit is necessary. So that's what you get.正如 Dirk 所指出的,formatC() 是另一种选择。
formatC(x = 5.999,数字 = 2,格式 = 'f')
As Dirk indicated, formatC() is another option.
formatC(x = 5.999, digits = 2, format = 'f')