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 use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits.
If we want to format the decimal places of one specific number (or a vector of numbers), we can use the format function in combination with the round function and the specification nsmall. Consider the following R syntax: format(round(x, 3), nsmall = 3) # Apply format function # "10.766"
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
.
format(round(x, 2), nsmall = 2)
For example:
format(round(1.20, 2), nsmall = 2) # [1] "1.20" format(round(1, 2), nsmall = 2) # [1] "1.00" format(round(1.1234, 2), nsmall = 2) # [1] "1.12"
A more general function is as follows where x
is the number and k
is the number of decimals to show. trimws
removes any leading white space which can be useful if you have a vector of numbers.
specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))
E.g.,
specify_decimal(1234, 5) # [1] "1234.00000" specify_decimal(0.1234, 5) # [1] "0.12340"
Discussion of alternatives:
The formatC answers and sprintf answers work fairly well. But they will show negative zeros in some cases which may be unwanted. I.e.,
formatC(c(-0.001), digits = 2, format = "f") # [1] "-0.00" sprintf(-0.001, fmt = '%#.2f') # [1] "-0.00"
One possible workaround to this is as follows:
formatC(as.numeric(as.character(round(-.001, 2))), digits = 2, format = "f") # [1] "0.00"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With