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.

Frequently asked questions

How does JavaScript handle decimal places?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Formatting Decimals" snippet in JavaScript uses `num.toFixed(digits)`.
Which code does the JavaScript example use?
The "Formatting Decimals" snippet uses `num.toFixed(digits)`, from the Numbers & Math section of the JavaScript cheat sheet.
Which stacks cover "decimal places" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Formatting Decimals": toFixed() returns a STRING, not a number. Wrap in Number() or use + to convert back: +total.toFixed(2)