rguides

trunc()

trunc(x)

The trunc() function truncates numeric values toward zero, removing the fractional part.

Syntax

trunc(x)

Parameters

ParameterTypeDefaultDescription
xnumericrequiredA numeric vector or scalar to truncate

Examples

Basic usage

# Truncate positive numbers
trunc(3.14)
# [1] 3

trunc(3.99)
# [1] 3

Negative numbers

# Truncate negative numbers (toward zero)
trunc(-2.7)
# [1] -2

trunc(-0.9)
# [1] 0

Comparison with floor and ceiling

x <- c(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5)

floor(x)
# [1] -3 -2 -1  0  1  2

ceiling(x)
# [1] -2 -1  0  1  2  3

trunc(x)
# [1] -2 -1  0  0  1  2

Common Patterns

Extracting integer part

# Get integer part of a number
trunc(123.456)
# [1] 123

# Works with negative numbers too
trunc(-123.456)
# [1] -123

Date/time operations

# Truncate POSIXct to date
dt <- as.POSIXct("2024-03-15 14:30:45")
trunc(dt, "days")
# [1] "2024-03-15"

# Truncate to hours
trunc(dt, "hours")
# [1] "2024-03-15 14:00:00"

Financial calculations

# Integer dollars from decimal prices
prices <- c(10.99, 20.50, 5.01)
trunc(prices)
# [1] 10 20  5

See Also