Absolute value

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Powers and Roots

JS · Numbers & Math
Syntax
base ** exponent
Math.sqrt(n)
Math.cbrt(n)
Math.pow(base, exp)
Example
console.log(2 ** 10);         // 1024
console.log(Math.sqrt(144));  // 12
console.log(Math.cbrt(27));   // 3
console.log(Math.abs(-42));   // 42

Note The ** operator is cleaner than Math.pow() and works with BigInt too: 2n ** 64n.

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 absolute value?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Powers and Roots" snippet in JavaScript uses `base ** exponent`.
Which code does the JavaScript example use?
The "Powers and Roots" snippet uses `base ** exponent`, from the Numbers & Math section of the JavaScript cheat sheet.
Which stacks cover "absolute value" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Powers and Roots": The ** operator is cleaner than Math.pow() and works with BigInt too: 2n ** 64n.