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

R ceiling() and floor() Functions - Rounding Up and Down

R ceiling() and floor() Functions - Rounding Up and Down

R Language Examples R Language Examples

R provides several rounding functions: ceiling() rounds up, floor() rounds down, and trunc() truncates toward zero.

These functions are often used in numeric discretization, binning, and resource allocation calculations.

The syntax of each function is as follows:

ceiling(x)   # 向上取整(不小于 x 的最小整数)

floor(x)     # 向下取整(不大于 x 的最大整数)

trunc(x)     # 向零方向截断

Parameter Description:

Example

x

<-

c

(

3.14

,

3.14

,

5.99

,

5.99

,

2.0

)

ceiling: round up

print

(

"ceiling (up):"

)

print

(

ceiling

(

x

)

)

floor: round down

print

(

"floor (down):"

)

print

(

floor

(

x

)

)

trunc: truncate toward zero

print

(

"trunc (toward zero):"

)

print

(

trunc

(

x

)

)

The output of the code above is:

[1] "ceiling(向上):"

[1]  4 -3  6 -5  2

[1] "floor(向下):"

[1]  3 -4  5 -6  2

[1] "trunc(向零截断):"

[1]  3 -3  5 -5  2

ceiling() is very useful in pagination calculations:

Example

Pagination calculation: display 20 records per page

total_items

<-

103

items_per_page

<-

20

Calculate the total number of pages needed (round up)

total_pages

<-

ceiling

(

total_items

/

items_per_page

)

print

(

paste

(

total_items,

"records per page"

, items_per_page,

           

"records, requiring a total of"

, total_pages,

"pages"

)

)

The output of the code above is:

[1] "103 条数据,每页 20 条,共需 6 页"

R Language Examples R Language Examples