Site icon R-bloggers

R Program to Format Decimal Places

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Example 1: Format Decimal Places in R Using sprintf()

num <- 1.34567

# use sprintf() to format decimal places of num
sprintf(num, fmt = '%#.4f') 

Output: [1] "1.3457"

In the above example, we’ve used the sprintf() function to print the given floating-point number num to 4 decimal places. The 4 decimal places are given by the format .4f.

This means, the function prints only up to 4 places after the dot (decimal places), and f means to print the floating-point number.


Example 2: Format Decimal Places in R Using format()

num <- 1.34567

# format decimal places using format()
format(num, digits = 5)

# Output: [1] "1.3457"

Here, we have used the format() function to format decimal places of num.

Since we have passed digits = 5 inside format(), the number of digits to be returned along with the number before decimal point is 5.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.