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"?
Thanks!
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"?
Thanks!
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()
.
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. Then as.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.