round, bround, ceil & floor
The rounding family. round rounds half away from zero to a given number of decimals; bround is banker's rounding (half to even); ceil always rounds up and floor always rounds down to a whole number.
def round(e: Column, scale: Int = 0): Column // half away from zero def bround(e: Column, scale: Int = 0): Column // half to even (banker's) def ceil(e: Column): Column def floor(e: Column): Column
1. round to N decimals
Round a line total to 2 decimal places — the everyday money case:
import org.apache.spark.sql.functions.round
orders.select(
$"product",
round($"amount" * $"qty", 2).as("total")
).show(4, false)2. ceil / floor
orders.select(
$"amount",
ceil($"amount").as("rounded_up"),
floor($"amount").as("rounded_down")
).show(4, false)3. bround — half to even
Banker's rounding reduces cumulative bias when you round millions of values — 2.5 rounds to 2, 3.5 rounds to 4 (always toward the even neighbour):
Seq(2.5, 3.5, 4.5).toDF("x").select(
round($"x").as("round"),
bround($"x").as("bround")
).show(false)| x | round | bround |
|---|---|---|
| 2.5 | 3 | 2 |
| 3.5 | 4 | 4 |
| 4.5 | 5 | 4 |
round(x) with no scale rounds to a whole number but keeps the column's type (a double stays a double, e.g. 50.0). To get an integer type, add .cast("int"). Negative scale rounds to the left of the decimal point — round($"n", -2) rounds to the nearest hundred.