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)
You can try my package formattable.
The good thing is,
x
is still a numeric vector and you can do more calculations with the same formatting.Even better, the digits are not lost, you can reformat with more digits any time :)
The function
formatC()
can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.You can format a number, say
x
, up to decimal places as you wish. Herex
is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:Here
format="f"
gives floating numbers in the usual decimal places say, xxx.xxx, anddigits
specifies the number of digits. By contrast, if you wanted to get an integer to display you would useformat="d"
(much likesprintf
).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.
I'm using this variant for force print K decimal places:
if you just want to round a number or a list, simply use
Then, data will be round to 2 decimal place.