Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (5.3k points)
edited by

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


The use of:


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)

1 Answer

0 votes
edited by

You can use the format function to format a number to only two decimal places in your code:

format(round(num, 2), nsmall = 2)

Here, nsmall is used to print the minimum number of digits to the right of the decimal point in formatting real/complex numbers in non-scientific formats

For example:

format(round(4.24560, 2), nsmall = 2) 

[1] "4.25" 

format(round(9.896560, 2), nsmall = 2) 

[1] "9.90"

Browse Categories