lokheart lokheart - 2 months ago 6
R Question

How to make "pretty rounding"?

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
?

Answer

Try either one of these:

> sprintf("%3.2f", round(5.9999, digits=2))
[1] "6.00
> sprintf("%3.2f", 5.999)  # no round needed either
[1] "6.00

There are also formatC() and prettyNum().