Reference · Math

round

signature
round(num | dec, int=, str=) -> num | dec

What it does

The number rounded. round(x) on an int or a float gives an int, a half going away from zero (round(2.5) is 3, round(-2.5) is -3). round(x, digits) of a float gives a float with at most that many decimals (up to 15), rounded from the float's shortest decimal, a tie away from zero, as format_number rounds; negative digits round to tens, hundreds and so on (round(1234.5678, -2) is 1200.0). An int with digits stays an int: itself for 0 or more digits, and to tens or hundreds for fewer. A decimal stays a decimal with exactly digits decimals, rounded half to even unless a mode is given as the third argument: half_even (the default), half_up (a half away from zero), half_down, up (away from zero), down (toward zero), ceiling or floor.

Examples

print(round(2.5), round(-2.5), round(2.4), round(2))print(round(3.14159, 2), round(1234.5678, 2))print(round(12.5m), round(13.5m), round(12.345m, 2), round(12.5m, 2))print(round(2.5m, 0, "half_up"), round(12.345m, 2, "half_up"), round(2.1m, 0, "ceiling"))
output
3 -3 2 23.14 1234.5712 14 12.34 12.503 12.35 3

Edge cases

print(round(2, 2), round(1234.5678, -2), round(1234.5m, -2), round(1255, -1), round(25, -1))print(round(1.005, 2), round(2.675, 2), round(-1.005, 2), round(1.005m, 2), round(1.005m, 2, "half_up"))print(round(12.5m), round(13.5m), round(-2.5m), round(0.5m))print(round(1e16), type_of(round(1e16)), round(float("nan")))print(round(2.5, 0), round(2.5), round(-7 / 2), round(9007199254740995 / 2))
output
2 1200.0 1200 1260 301.01 2.68 -1.01 1.00 1.0112 14 -2 010000000000000000 int NaN3.0 3 -4 4503599627370498

Errors

An argument that is not a number is a runtime error, not an error value, and so is a rounding mode on a float: the modes are for decimals only. An unknown mode names the seven that exist. Digits that are not an int (a float, null) are a runtime error too.

this one fails
print(round(2.5, 1, "half_up"))
output
line 1: `round` takes a rounding mode for a dec only: convert with dec(x)
this one fails
print(round(2.5m, 1, "nearest"))
output
line 1: `round`: unknown rounding "nearest" (one of half_even, half_up, half_down, up, down, ceiling or floor)

Chaining

print([1.5, 2.5, 3.5] | map(round))print(19.99m * 3 * 0.21m | round(2))print([1.26, 2.71] | map((x) => round(x, 1)))
output
[2, 3, 4]12.59[1.3, 2.7]

See also

floor, ceil, abs, dec, int, format_number

Thread
9Useful? Like it, or add to its thread below.

Thread 0 posts

On round(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo