How to round() a value in R
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.
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
numberthat is to be rounded off. -
The parameter
ndigitsis the number of decimal places to which the above number needs to be rounded off. This is an optional parameter. Its default value is0. Ifndigitsis omitted, thenround()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: positivea <- round(9.8923,2);print(paste0("round(9.8923,2): ", a))#number: negative ndigits: positiveb <- round(-9.8923,2);print(paste0("round(-9.8923,2): ", b))#number: positive ndigits: negativec <- 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: negativee <- round(-923.8923,-2);print(paste0("round(-923.8923,-2): ", e))f <- round(-989.8923,-2);print(paste0("round(-989.8923,-2): ", f))# no ndigitsg <- round(9.8923);print(paste0("round(9.8923): ", g))h <- round(-9.8923);print(paste0("round(-9.8923): ", h))