Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

math
round()
r
communitycreator

How to round() a value in R

harris910

The round() function rounds off a number to a specified number of decimal places.

Figure 1, below, shows a visual representation of the round() function.

Figure 1: Visual representation of the round() function

Syntax


round(num, ndigits);

// where num is the number which is to be rounded off

// where ndigits is the number of decimal places

Parameter

This function requires two parameters:

  • It requires a number that is to be rounded off.

  • The parameter ndigits is the number of decimal places to which the above number needs to be rounded off. This is an optional parameter. Its default value is 0. If ndigits is omitted, then round() returns the nearest integer value of a number.

Return value

The round() function returns the number rounded off to the specified number of decimal places.

If you input a negative value (-n) in the ndigits, then n digits to the left of the decimal will be rounded off.

Code

#number: postive ndigits: positive
a <- round(9.8923,2);
print(paste0("round(9.8923,2): ", a))

#number: negative ndigits: positive
b <- round(-9.8923,2);
print(paste0("round(-9.8923,2): ", b))

#number: positive ndigits: negative
c <- round(923.8923,-2);
print(paste0("round(923.8923,-2): ", c))

d <- round(989.8923,-2);
print(paste0("round(989.8923,-2): ", d))

#number: negative ndigits: negative
e <- round(-923.8923,-2);
print(paste0("round(-923.8923,-2): ", e))

f <- round(-989.8923,-2);
print(paste0("round(-989.8923,-2): ", f))

# no ndigits
g <- round(9.8923);
print(paste0("round(9.8923): ", g))

h <- round(-9.8923);
print(paste0("round(-9.8923): ", h))

RELATED TAGS

math
round()
r
communitycreator
RELATED COURSES

View all Courses

Keep Exploring