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.

Frequently asked questions

How do you round number?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Rounding" snippet in JavaScript uses `Math.round(n) | Math.floor(n) | Math.ceil(n) | Math.trunc(n)`.
Which code does the JavaScript example use?
The "Rounding" snippet uses `Math.round(n) | Math.floor(n) | Math.ceil(n) | Math.trunc(n)`, from the Numbers & Math section of the JavaScript cheat sheet.
Which stacks cover "round number" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Rounding": 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.