76

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
zx8754
  • 46,390
  • 10
  • 104
  • 180
Marco
  • 9,004
  • 7
  • 32
  • 49

2 Answers2

99

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.

Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
Chase
  • 65,190
  • 17
  • 140
  • 160
64

When you print it out, you should be able to do:

formatC( round( 5.2, 3 ), format='f', digits=3 )
tim_yates
  • 161,005
  • 26
  • 328
  • 327
  • 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 Mar 28 '11 at 12:25
  • How about something that works both for printing and non-printing purposes? – rnorouzian Feb 22 '17 at 22:03
  • 1
    I don't understand what you mean – tim_yates Feb 23 '17 at 00:04
  • 1
    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. – dudu Jan 02 '18 at 11:20