[R] specify the number of decimal numbers

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu May 14 18:32:27 CEST 2009

(Ted Harding) wrote:
> This happens also when you use C's fprintf and sprintf (at any rate
> in my gcc):

r's printing routines (e.g., print, sprintf, cat, anything else?) seem
to rely on the underlying c sprintf, with no prior r-implemented
rounding.  hence they import into r whatever standards-related problems
may the c counterpart have.

>   #include <stdio.h>
>   #include <math.h>

why math.h?

>   main(argc,argv) int argc; char **argv;
>   {
>   fprintf(stdout, "%.1f\n", 0.15);
>   fprintf(stdout, "%.1f\n", 0.05);
>   fprintf(stdout, "%.2f\n", 0.15);
>   fprintf(stdout, "%.2f\n", 0.05);
>   }
>   cc -o testprint3 testprint3.c
>   ./testprint
>   0.1
>   0.1
>   0.15
>   0.05
> (with similar output when printing a string formatted by sprintf).

indeed.  i posted a similar example in reaction to the original 'excel
bug' response.

> So, in so far a R relies on the compiler's implementation of the
> *printf functions, this can hardly be put right withbout re-writing
> [g]cc!

it does (seems to), but probably shouldn't, if excel bugs are to be
avoided.  however, passing the input from sprintf('%.1f', x) through
round to do the rounding would require some work to first parse the
format and decide the number of decimal digits.  not that it's undoable.


More information about the R-help mailing list