0

I'm looking for a quick and simple way to reduce the precision of a number in R, either for display on a chart or for inclusion in a report (text or table).

My go-to function is sprintf(), but it doesn't appear that any of the format specifiers are sufficiently general to handle all possible cases, even though what I'm looking for is fairly common (it's what we are all taught in school).

For example, if I want to round to 3 significant digits, I'm looking for a formula that could take:

  • 1,239,451 and return 1,240,000
  • -12.1257 and return -12.1
  • .0681 and return .0681
  • 5 and return 5

Note: This answer provides what I believe is a javascript implementation of just such a function, but I'm no javascript expert, and the syntax of some of the functions used is not obvious to me. Also, I'm curious if I've missed some built-in functionality of base R or a common library to do just this.

Community
  • 1
  • 1
mac
  • 1,935
  • 20
  • 33
  • 3
    Searching for "[r] significant digits" produces lots of answers: http://stackoverflow.com/q/3245862/271616, http://stackoverflow.com/q/3443687/271616, http://stackoverflow.com/q/2287616/271616, http://stackoverflow.com/q/1491124/271616. It can also be found in `?round`. – Joshua Ulrich Jul 29 '13 at 20:44

1 Answers1

4
> formatC( signif(1239451, digits=3), big.mark=",", format="fg")
[1] "1,240,000"
> formatC( signif(-12.1257, digits=3), big.mark=",", format="fg")
[1] "-12.1"
> formatC( signif(.0581, digits=3), big.mark=",", format="fg")
[1] "0.0581"
> formatC( signif(5, digits=3), big.mark=",", format="fg")
[1] "5"
IRTFM
  • 240,863
  • 19
  • 328
  • 451