Round number

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Rounding

JS · Numbers & Math
syntax
Math.round(n) | Math.floor(n) | Math.ceil(n) | Math.trunc(n)
example
const price = 19.872;
console.log(Math.round(price));  // 20
console.log(Math.floor(price));  // 19
console.log(Math.ceil(price));   // 20
console.log(Math.trunc(price));  // 19
console.log(Math.trunc(-3.7));   // -3 (not -4)

Note trunc() simply removes decimals (towards zero). floor() rounds towards negative infinity. They differ for negative numbers: floor(-3.2) = -4 but trunc(-3.2) = -3.

PYPython

abs() and round()

PY · Numbers
syntax
abs(number)
round(number, ndigits)
example
print(abs(-42.5))
print(round(3.14159, 2))
print(round(2.5))
print(round(3.5))
output
42.5
3.14
2
4

Note round() uses banker's rounding — it rounds to the nearest even number when the value is exactly halfway. This surprises many developers.