Skip to contents

Round a numeric vector to any number, rounded up by default (round_up = TRUE).

Usage

round_to(x, to = 0.2, round_up = TRUE)

Arguments

x

Vector of numbers to round.

to

Number to round x to. A numeric scalar.

round_up

Whether to round a remainder of exactly to / 2 up or not. Set to FALSE in order to round off.

Value

A numeric vector of the same length as x.

Details

This function's precision is limited to 15 significant digits in order to account for the limits of R's floating point representation.

A computationally more efficient alternative would be the unexported scales:::round_any() which drives scales::number() – with the drawback that it lacks control of rounding up exact remainders of accuracy / 2, i.e. it always rounds off.

See also

prettyunits::pretty_round()

Other statistical computing / numeric functions: safe_max(), safe_min(), safe_seq_len(), stat_mode()

Examples

vals = c(0.025, 0.1, 0.1999, 0.099999, 0.49, 0.55, 0.5, 0.9, 1)
vals |> pal::round_to(to = 0.05)
#> [1] 0.05 0.10 0.20 0.10 0.50 0.55 0.50 0.90 1.00
vals |> pal::round_to(to = 0.05,
                      round_up = FALSE)
#> [1] 0.00 0.10 0.20 0.10 0.50 0.55 0.50 0.90 1.00