>From the help page of format, nsmall should control the number of digits.> format(0.123456789, nsmall = 10)[1] "0.1234567890"> format(0.123456789, nsmall = 1)[1] "0.1234568"> format(0.123456789, nsmall = 2)[1] "0.1234568"> format(0.123456789, nsmall = 8)[1] "0.12345679" It adds zeros fine but for format(0.123456789, nsmall = 1) I want the result to be 0.1. I want to format numbers with a fixed number of digits. A combination of round and format + nsmall does the job. sprintf will do it too, but I wondered if the current implementation of nsmall in format is correct. Thanks, Adrian
Prof Brian Ripley
2006-Feb-14 07:35 UTC
[R] Correct (was 'weird') behavior of nsmall in format
On Mon, 13 Feb 2006, Adrian Dragulescu wrote:>> From the help page of format, nsmall should control the number of digits.That's not a quote from the help page.>> format(0.123456789, nsmall = 10) > [1] "0.1234567890" >> format(0.123456789, nsmall = 1) > [1] "0.1234568" >> format(0.123456789, nsmall = 2) > [1] "0.1234568" >> format(0.123456789, nsmall = 8) > [1] "0.12345679" > > It adds zeros fine but for format(0.123456789, nsmall = 1) I want the > result to be 0.1. > > I want to format numbers with a fixed number of digits. A combination of > round and format + nsmall does the job. sprintf will do it too, but I > wondered if the current implementation of nsmall in format is correct.It is, but your reading of the help page is not. The help page actually says digits: how many significant digits are to be used for numeric and complex 'x'. The default, 'NULL', uses 'getOption(digits)'. This is a suggestion: enough decimal places will be used so that the smallest (in magnitude) number has this many significant digits, and also to satisfy 'nsmall'. (For the intepretation for complex numbers see 'signif'.) nsmall: number of digits which will always appear to the right of the decimal point in formatting real/complex numbers in non-scientific formats. Allowed values are '0 <= nsmall < 20'. Note the `always'. -- Brian D. Ripley, ripley at stats.ox.ac.uk 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