tags:

views:

189

answers:

5

I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that?

x <- 1.128347132904321674821

EDIT:

The use of:

options(digits=2)

Has been suggested as a possible answer. Is there a way to specify this within a script for one-time use? When I add it to my script it doesn't seem to do anything different and I'm not interested in a lot of re-typing to format each number (I'm automating a very large report).

--

Answer: round(x, digits=2)

+2  A: 

Looks to me like to would be something like

format(1.128347132904321674821, 2)

Per a little online help.

Tim Meers
I found this, but it requires a package, I'm looking for something within the base package.
Brandon Bertelsen
@brandon, format() is part of base. Open up R and type ?format ... no packages needed.
JD Long
Hrmmm, did you look at what this outputs? [1] "1.128347" otherwise, you're quite right about it being in the base package, my bad.
Brandon Bertelsen
Perhaps try `format.default(x, digits = 2)` just a shot in the dark though based on the link provided. That info is some what lacking from what I normally read for documentation, I expected to see the printed outputs as well.
Tim Meers
Just noticed that your link points to tutoR documentation, which is not part of the base.
Brandon Bertelsen
+1  A: 

Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.
Xavier V.
Is there any way to set this dynamically when running a script?
Brandon Bertelsen
This works for outputting within the R console, but doesn't work within my script (they still come out with .1289273982)
Brandon Bertelsen
+2  A: 

Check functions prettyNum, format

to have trialling zeros (123.1240 for example) use sprintf(x, fmg='%#.4g')

ilya
+1  A: 

Well, the two that come to mind are

fixed(1.128347132904321674821, digits=2)

or if you prefer siginificant digits to fixed digits then;

signif(1.128347132904321674821,digits=3)
PaulHurleyuk
Thanks Paul. These two weren't exactly what I was looking for, but signif led me to round() which is exactly what I needed. Cheers,
Brandon Bertelsen
+1  A: 

Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.

nullglob
Confirmed, it's just for an example. I mashed the keyboard.
Brandon Bertelsen