I think you missed the function called 'format'. R's internal print
routines (used by format) calculate the format passed to (C level) sprintf
based on the input, including 'digits'. Just make sure you pass one
number at a time to format() if you don't want a common layout for all the
numbers.
On Thu, 14 Aug 2008, [EMAIL PROTECTED] wrote:
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
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
--
Brian D. Ripley, [EMAIL PROTECTED]
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.