[R] specify the number of decimal numbers

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu May 14 14:04:34 CEST 2009


On 14-May-09 11:40:21, lehe wrote:
> Hi,
> I was wondering how to specify the number of decimal numbers in my
> computation using R? I have too many decimal numbers for my result,
> when I convert them to string with as.character, the string will
> be too long.
> Thanks and regards!

Since you say you want them to end up as character strinngs,
it would seem that sprintf() is the ideal tool for the job.

1. Read ?sprintf

2. Examples:

  pi
# [1] 3.141593

  sprintf("%.3f",pi)
# [1] "3.142"

# sprintf("%10.3f",pi)
  [1] "     3.142"

  sprintf("%010.3f",pi)
# [1] "000003.142"

  sprintf("%025.17f",pi)
# [1] "0000003.14159265358979312"

So you can do pretty much what you want, in terms of output format.
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 14-May-09                                       Time: 13:04:30
------------------------------ XFMail ------------------------------




More information about the R-help mailing list