Skip to content

Round underlying floating point data by decimals digits

Source code

Description

Round underlying floating point data by decimals digits

Usage

<Expr>$round(decimals = 0L, mode = c("half_to_even", "half_away_from_zero"))

Arguments

decimals Number of decimals to round by.
mode Rounding mode. One of the following:
  • “half_to_even” (default): round to the nearest even number;
  • “half_away_from_zero”: round to the nearest number away from zero.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(a = c(0.33, 0.52, 1.02, 1.17))
df$select(pl$col("a")$round(1))
#> shape: (4, 1)
#> ┌─────┐
#> │ a   │
#> │ --- │
#> │ f64 │
#> ╞═════╡
#> │ 0.3 │
#> │ 0.5 │
#> │ 1.0 │
#> │ 1.2 │
#> └─────┘
df <- pl$DataFrame(
  f64 = c(-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5),
  d = c("-3.5", "-2.5", "-1.5", "-0.5", "0.5", "1.5", "2.5", "3.5")
)$cast(d = pl$Decimal(scale = 1))

df$with_columns(
  pl$all()$round(mode = "half_away_from_zero")$name$suffix("_away"),
  pl$all()$round(mode = "half_to_even")$name$suffix("_to_even"),
)
#> shape: (8, 6)
#> ┌──────┬──────────────┬──────────┬──────────────┬─────────────┬──────────────┐
#> │ f64  ┆ d            ┆ f64_away ┆ d_away       ┆ f64_to_even ┆ d_to_even    │
#> │ ---  ┆ ---          ┆ ---      ┆ ---          ┆ ---         ┆ ---          │
#> │ f64  ┆ decimal[*,1] ┆ f64      ┆ decimal[*,1] ┆ f64         ┆ decimal[*,1] │
#> ╞══════╪══════════════╪══════════╪══════════════╪═════════════╪══════════════╡
#> │ -3.5 ┆ -3.5         ┆ -4.0     ┆ -4.0         ┆ -4.0        ┆ -4.0         │
#> │ -2.5 ┆ -2.5         ┆ -3.0     ┆ -3.0         ┆ -2.0        ┆ -2.0         │
#> │ -1.5 ┆ -1.5         ┆ -2.0     ┆ -2.0         ┆ -2.0        ┆ -2.0         │
#> │ -0.5 ┆ -0.5         ┆ -1.0     ┆ -1.0         ┆ -0.0        ┆ 0.0          │
#> │ 0.5  ┆ 0.5          ┆ 1.0      ┆ 1.0          ┆ 0.0         ┆ 0.0          │
#> │ 1.5  ┆ 1.5          ┆ 2.0      ┆ 2.0          ┆ 2.0         ┆ 2.0          │
#> │ 2.5  ┆ 2.5          ┆ 3.0      ┆ 3.0          ┆ 2.0         ┆ 2.0          │
#> │ 3.5  ┆ 3.5          ┆ 4.0      ┆ 4.0          ┆ 4.0         ┆ 4.0          │
#> └──────┴──────────────┴──────────┴──────────────┴─────────────┴──────────────┘