[R] 2 significant digits

Marc Schwartz marc_schwartz at me.com
Tue Nov 10 17:39:34 CET 2009


On Nov 10, 2009, at 10:22 AM, carol white wrote:

> Hi,
> How to represent a rounded number ending with 0 with 2-significant  
> digits? If I have for ex, 0.8031 and I use signif or round with  
> digits = 2, I'll get 0.8. If I use format, I get character type  
> (even if I pass number as parameter) and if I convert with  
> as.numeric, I'll lose one significant digit (0):
>
>> format(13.7, nsmall = 2)
> [1] "13.70"
>> as.numeric( format(13.7, nsmall = 2))
> [1] 13.7
>
>
> Regards,
>
> Carol



See ?sprintf if you want to force two decimal places, as opposed to  
two significant digits:

 > sprintf("%.2f", 0.8031)
[1] "0.80"

A trailing zero is not a significant digit, hence it will not be  
displayed if you are formatting based upon significant digits, as  
opposed to a fixed number of decimal places.

If you want to force the formatting of a numeric value for output, it  
will end up being a character, which should not be a problem, since  
you are presumably looking to display or output the number for  
reading, not to be used for subsequent calculations.

Conceptually, you need to separate how R stores numeric values  
internally, versus how numeric values are displayed (printed) during  
output. By default, R stores numeric values internally as double  
precision floats to allow for mathematical calculations to be  
performed on those values.

The printing of those numbers for output in an R console or GUI, is by  
default based upon significant digits (see ?print.default), but you  
can alter that behavior using various functions such as sprintf, to  
enable "pretty output" for formatted reports and tables, etc.

HTH,

Marc Schwartz




More information about the R-help mailing list