How to Round Numbers in R
When you round numbers in R, four vectorized base functions cover every case: round(), floor(), ceiling(), and trunc(). R uses banker’s rounding in round() — values exactly halfway between two integers round to the nearest even integer, so round(0.5) returns 0 and round(1.5) returns 2. This is statistically unbiased but differs from the round‑half‑up rule taught in most introductory courses.
round(3.14159, 2) # 3.14 - round to 2 digits
ceiling(3.14) # 4 - always round up
floor(3.99) # 3 - always round down
trunc(3.99) # 3 - drop fractional part
# Apply to a data frame column
df <- data.frame(price = c(10.456, 20.999, 15.5))
df$price <- round(df$price, 2)
floor() always rounds down, ceiling() always rounds up, and trunc() rounds toward zero (down for positive numbers, up for negative). Banker’s rounding is statistically unbiased but surprises users who expect the traditional round‑half‑up rule. For financial calculations requiring round‑half‑up behavior, use round(x + 1e-9) or a custom function. For dplyr pipelines, df %>% mutate(price = round(price, 2)) fits cleanly inside mutate(). When formatting output for display, sprintf("%.2f", x) rounds and converts to character in one step. For significant digits instead of decimal places, signif(12345, digits = 3) returns 12300. The zoo package provides na.trim() and na.approx() for rounding in the context of time series imputation.
See also
- round(), Round to specified digits
- floor() / ceiling(), Round down or up