Decimal places

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Formatting Decimals

JS · Numbers & Math
syntax
num.toFixed(digits)
num.toPrecision(precision)
example
const total = 29.5;
console.log(total.toFixed(2));       // "29.50"
console.log((0.1 + 0.2).toFixed(2)); // "0.30"

const big = 123456.789;
console.log(big.toPrecision(6));     // "123457"

Note toFixed() returns a STRING, not a number. Wrap in Number() or use + to convert back: +total.toFixed(2)

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.