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)
Looks to me like to would be something like
Per a little online help.
Background: Some answers suggested on this page (e.g.,
signif
,options(digits=...)
) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.Solution:
The following code shows exactly two decimal places for the number
x
.For example:
A more general function is as follows where
x
is the number andk
is the number of decimals to show.trimws
removes any leading white space which can be useful if you have a vector of numbers.E.g.,
for 2 decimal places assuming that you want to keep trailing zeros
which gives
As @mpag mentions below, it seems R can sometimes give unexpected values with this and the round method e.g. sprintf(5.5550, fmt='%#.2f') gives 5.55, not 5.56
Something like that :
Definition of digits option :
Well, the two that come to mind are
or if you prefer siginificant digits to fixed digits then;
Check functions prettyNum, format
to have trialling zeros (123.1240 for example) use
sprintf(x, fmt='%#.4g')