[R] Format with n significant figures / digits

wannymahoots at gmail.com
2008-08-14T13:37:44Z

Hi everyone,

I can't figure out how to format numbers to have a certain number of
significant figures (as opposed to decimal places) without using
scientific notation and including trailing zeros if necessary.

e.g. I would like to achieve the following:
0.800001  --->  0.8000
123.4567    --->    123.4
0.1234567  --->    0.1234
7.654321    --->    7.654
7654321     --->    7654000

It seems like it should be simple, but I can't seem to do this using
sprintf.  Specifically, I get the following outputs:

 > vec = c(0.800001, 123.4567, 0.1234567, 7.654321, 7654321)

 > #  this specifies precision after decimal point, rather than
significant figures
 > sprintf("%.4f", vec)
[1] "0.8000"       "123.4567"     "0.1235"
"7.6543"
"7654321.0000"

 > #  uses scientific notation, but significant figures are correct
 > sprintf("%.3e", vec)
[1] "8.000e-01" "1.235e+02" "1.235e-01"
"7.654e+00" "7.654e+06"

 > #  correct number of significant figures, and without scientific
notation, but has trailing zeros on large numbers
 > sprintf("%.4f", sprintf("%.3e", vec))
[1] "0.8000"       "123.5000"     "0.1235"
"7.6540"
"7654000.0000"

Am I missing something obvious and can someone help me?

Many thanks