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 )
Share:
44,060

Related videos on Youtube

Marco
Author by

Marco

Updated on July 05, 2022

Comments

  • Marco
    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
    Marco about 13 years
    Thank 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
    Marco about 13 years
    @Chase: Is there the possibility to output a numeric value instead of a character???
  • daroczig
    daroczig about 13 years
    @Marco: I think no, a numeric value does not have trailing zeros.
  • tim_yates
    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
    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
    rnorouzian about 7 years
    If it's not for printing purposes what could be used instead of sprintf(...)?
  • rnorouzian
    rnorouzian about 7 years
    How about something that works both for printing and non-printing purposes?
  • tim_yates
    tim_yates about 7 years
    I don't understand what you mean
  • dudu
    dudu over 6 years
    Is 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
    zx8754 almost 5 years
    @rnorouzian then we use as is: 5.2.