R ceiling() and floor() functions - Rounding up and down

R 语言实例R language examples

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

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

The syntax format of each function is as follows:

ceiling(x)   # 向上取整(不小于 x 的最小整数)
floor(x)     # 向下取整(不大于 x 的最大整数)
trunc(x)     # 向零方向截断

Parameter description:

  • xInput a numeric value or numeric vector.

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 (truncate toward zero):")
print(trunc(x))

Executing the above code produces the following result:

[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: 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, total", total_pages, "pages"))

Executing the above code produces the following result:

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

R 语言实例R language examples

Other extensions