Math Methods
Math Methods are grouped by functionality for clarity, and all operate within JavaScript’s 64-bit floating-point arithmetic, which may introduce minor precision errors (similar to Number.EPSILON considerations).
Arithmetic & Rounding Methods
These methods handle basic arithmetic and rounding operations.
abs(x)
Returns the absolute value of x
.
Example:
console.log(Math.abs(-5)); // 5
console.log(Math.abs(3)); // 3
ceil(x)
Rounds x
up to the nearest integer.
Example:
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(-4.1));// -4
floor(x)
Rounds x
down to the nearest integer.
Example:
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(-4.9));// -5
round(x)
Rounds x
to the nearest integer (half rounds up).
Example:
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
trunc(x)
Removes the fractional part of x
, returning the integer part.
Example:
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
sign(x)
Returns the sign of x
:
1
→ positive1
→ negative0
→ zero0
→ negative zeroNaN
→ not a number
Example:
console.log(Math.sign(-42)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(15)); // 1
fround(x)
Rounds x
to the nearest 32-bit single-precision float.
Example:
console.log(Math.fround(1.337)); // 1.337000012
console.log(Math.fround(0.1 + 0.2)); // 0.30000001192092896