Rounding numbers in R

R introduction Mathematical functions
Round numbers in R with round(), floor(), ceiling(), trunc() and signif() functions

R provides several functions for rounding decimal numbers. In this tutorial you will learn the usage of the different functions to round values in R, this is, round, ceiling, floor, trunc and signif functions.

The round function

The most common function to round values in R is the round command. By default, this function will round the decimals to the nearest integer, except when rounding off a 5, where the value will be rounded to the nearest even integer.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

round(x)
2   4   6   9  -2  -8 -11

The round function not always rounds to the nearest whole number, as it takes the rule of: “go to the even digit”. This implies, for instance, that round(4.5) is 4 but round(5.5) is 6.

However, the main use case for this function is to round values to a specific number of decimal places with an argument named digits. For instance, if you want to round to two decimal places you can pass a 2 to digits:

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

round(x, digits = 2)
 2.00   4.50   5.65   9.18  -1.50  -8.35 -10.78

Note that you can also input negative numbers to digits. In this scenario the numbers will be rounded to a power of ten, meaning that -1 will round the value to the nearest ten, -2 will round to the nearest hundred and so on.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

round(x, digits = -1)
0   0  10  10   0 -10 -10

The floor function

The floor function will round down the values to the largest integer not greater than the value itself. See the example below for some clarification.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

floor(x)
2   4   5   9  -2  -9 -11

The ceiling function

The opposite function for floor is ceiling, which will round up the values to the smallest integer not less than the value itself.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

ceiling(x)
2   5   6  10  -1  -8 -10

The trunc function

The trunc function is a rounding function that removes the decimal places, returning only the integers of the values.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

trunc(x)
2   4   5   9  -1  -8 -10

The signif function

The last function for rounding numbers in R is signif, which will round the values to the specified number of significant digits (6 by default).

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

signif(x)
2.0000   4.5000   5.6534   9.1800  -1.5000  -8.3500 -10.7800

This function also allow you to specify the desired number of significant digits with digits argument.

x <- c(2, 4.5, 5.6534, 9.18, -1.5, -8.35, -10.78)

signif(x, digits = 3)
2.00   4.50   5.65   9.18  -1.50  -8.35 -10.80