80

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
  • 52,746
  • 12
  • 114
  • 209
Marco
  • 9,334
  • 7
  • 33
  • 51

2 Answers2

108

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
  • 178,213
  • 47
  • 333
  • 501
Chase
  • 67,710
  • 18
  • 144
  • 161
68

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

formatC( round( 5.2, 3 ), format='f', digits=3 )
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 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
  • 3
    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
  • Previously, I rounded like that but stopped because I thought there was an unnecessary step with the round() function. Do you remember why we are/were doing this: formatC(round( 5.455, 2), format='f', digits=2 ) and not this: formatC(5.455, format='f', digits=2 ) It seems as if both are rounding according to the IEEE standard (next even number). – Poza Jun 17 '23 at 11:48