Keeping trailing zeros
44,060
Solution 1
If this is for printing purposes, sprintf
is what you are after:
> sprintf("%.3f", round(5.2,3))
[1] "5.200"
See ?sprintf
for formatting details.
Solution 2
When you print it out, you should be able to do:
formatC( round( 5.2, 3 ), format='f', digits=3 )
Related videos on Youtube
Author by
Marco
Updated on July 05, 2022Comments
-
Marco almost 2 years
I would like to keep trailing zeros, for example, if I type:
round(5.2, 3)
I would like the output to be:
5.200
-
Marco about 13 yearsThank you. I am sorry, I cannot accept more than one answer. I have chosen to accept the previous one since Chase has a lower reputation score. However, your solution is very good as well. Thank you again!
-
Marco about 13 years@Chase: Is there the possibility to output a numeric value instead of a character???
-
daroczig about 13 years@Marco: I think no, a numeric value does not have trailing zeros.
-
tim_yates about 13 years@Marco
5.2
==5.200
they are the same number, the only difference is how the number is represented as a String -
Marco about 13 years@tim_yates: Yes, of course this is the same. The reason why I was wondering is, as it was suspected, is printing purpose.
-
rnorouzian about 7 yearsIf it's not for printing purposes what could be used instead of
sprintf(...)
? -
rnorouzian about 7 yearsHow about something that works both for printing and non-printing purposes?
-
tim_yates about 7 yearsI don't understand what you mean
-
dudu over 6 yearsIs there anything that could be changed using 'options()' in order to keep trailing zeros? I understand 5.2 == 5.200 but, in my case, for visual consitency it would be nice to keep trailing zeros. Since I am using annotate with 'parse=T' a string such as provided by 'formatC' isn't enough.
-
zx8754 almost 5 years@rnorouzian then we use as is:
5.2
.