4

I have a number like 0.5, I would like to keep two digits in 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

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
Eva
  • 917
  • 4
  • 18
  • 23

2 Answers2

3

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.

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
2

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"
Greg
  • 11,564
  • 5
  • 41
  • 27