The JavaScript Math object allows you to perform mathematical tasks on numbers. Unlike other objects, the Math object has no constructor. All properties and methods of Math are static.
JavaScript provides several mathematical constants that you can access via the Math object.
Math.PI — Approx. 3.14159Math.E — Euler's numberMath.SQRT2 — Square root of 2Math.LN10 — Natural logarithm of 10There are 4 common ways to round a number to an integer:
| Method | Description |
|---|---|
Math.round(x) |
Returns x rounded to its nearest integer |
Math.ceil(x) |
Returns x rounded up to its nearest integer |
Math.floor(x) |
Returns x rounded down to its nearest integer |
Math.trunc(x) |
Returns the integer part of x (removes decimals) |
Returns the value of x to the power of y.
Returns the square root of x.
Returns the absolute (positive) value of x.
Finds the lowest or highest value in a list.
This method checks if a number is negative, null, or positive. It returns -1 (negative), 0 (null), or 1 (positive).
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1
new Math() is requiredMath.floor() for reliable "downwards" roundingMath.PI is the most common constant for geometry
calculationsMath.min() and Math.max()
can take any number of argumentsMath.trunc() is safer for simply removing decimals than
rounding