Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R round() Function - Rounding and Truncation

R round() Function - Rounding and Truncation

R Language Examples R Language Examples

The R round() function is used to round numbers, with an option to specify the number of decimal places.

The syntax of the round() function is as follows:

round(x, digits = 0)

Parameter Description:

Example

Create a numeric vector

x

<-

c

(

3.14159

,

2.71828

,

1.41421

,

5.6789

)

Round to an integer

print

(

round

(

x

)

)

Keep 2 decimal places

print

(

round

(

x, digits

=

2

)

)

Keep 3 decimal places

print

(

round

(

x, digits

=

3

)

)

The output of the code above is:

[1] 3 3 1 6

[1] 3.14 2.72 1.41 5.68

[1] 3.142 2.718 1.414 5.679

R also provides several other rounding functions, each with different behavior:

Example

x

<-

c

(

3.7

,

3.7

,

3.2

,

3.2

)

ceiling: round up (the smallest integer not less than x)

print

(

"ceiling rounds up:"

)

print

(

ceiling

(

x

)

)

floor: round down (the largest integer not greater than x)

print

(

"floor rounds down:"

)

print

(

floor

(

x

)

)

trunc: truncate toward zero

print

(

"trunc truncation:"

)

print

(

trunc

(

x

)

)

signif: keep significant digits

print

(

"signif(pi, 4) 4 significant digits:"

)

print

(

signif

(

pi

,

4

)

)

The output of the code above is:

[1] "ceiling 向上取整:"

[1]  4 -3  4 -3

[1] "floor 向下取整:"

[1]  3 -4  3 -4

[1] "trunc 截断:"

[1]  3 -3  3 -3

[1] "signif(pi, 4) 4位有效数字:"

[1] 3.142

R Language Examples R Language Examples