A familiar failure exposes the issue: 0.1 + 0.2 is not represented exactly, so direct equality can mislead. Math supplies constants and numeric operations, while floating-point representation explains the result. section 3.1.1
Use Math.abs to measure a difference, then compare it with an appropriate tolerance. Number.EPSILON works for nearby values; scaling the tolerance by operand magnitude handles larger numbers more carefully. section 3.1.1
The namespace groups constants and common numeric operations:
- Math.PI and Math.E provide familiar mathematical constants. section 3.1.1
- Math.round, Math.floor, and Math.ceil choose different integer-rounding behaviors. section 3.1.1
- Math.pow and Math.sqrt provide exponentiation and square roots; Math.pow(m, n) matches m ** n. section 3.1.1
- Math.sin and Math.cos operate on radians, while Math.random returns a pseudo-random number between zero and one. section 3.1.1
Approximate comparison
function almostEqual(a, b) { return Math.abs(a - b) < Number.EPSILON; } console.log(almostEqual(0.1 + 0.2, 0.3)); // true section 3.1.1
|
Constants
|
Description
|
|
Math.PI
|
The ratio of a circle’s
circumference to its diameter (3.141592…)
|
|
Math.E
|
Euler’s number (2.718281…)
|
|
Operations
|
Description
|
|
Math.round(n)
|
Rounds to the nearest
integer
|
|
Math.floor(n)
|
Rounds down to the nearest
integer
|
|
Math.ceil(n)
|
Rounds up to the nearest
integer
|
|
Math.abs(n)
|
Returns the absolute value
|
|
Math.pow(m,
n)
|
Raises m to the nth power,
same as m ** n
|
|
Math.sqrt(n)
|
The square root of n
|
|
Math.sin(n),
Math.cos(n)
|
Work with radians
|
|
Math.random()
|
Return a pseudo-random
number between 0 and 1
|
Browse the constants and operations with their concise definitions. section 3.1.1
