I have a number like 0.5, I would like to keep two digits 开发者_如何学JAVAin order to make the number 0.50. While the last digit is zero, so it always cannot appear.
I have used round(0.5,2) but it doesn't work
You can cheat by using:
y <- 0.5
formatC(round(y,2),2,format="f")
Note that this changes to character. Hence, it's for display purposes only.
Another option is to use sprintf
y <- 0.5
sprintf("%0.2f", round(y, 2))
[1] "0.50"
EDIT: According to Wojciech Sobala (below)
sprintf("%0.2f", y)
should be sufficient.
sprintf("%0.2f", 0.478)
[1] "0.48"
精彩评论