Math: Rounding, Clamping, and ConstantsThe built-in JavaScript Math object provides constants and static methods for rounding numbers, finding extremes, and running geometry calculations. Unlike Date or Array, Math is a static namespace object, so you never call new Math().
Choosing the right rounding method matters most when handling negative numbers, because Math.floor() and Math.trunc() behave differently below zero:
| Method | 4.7 |
4.2 |
-4.2 |
Behavior |
|---|---|---|---|---|
Math.round(x) |
5 |
4 |
-4 |
Nearest integer |
Math.ceil(x) |
5 |
5 |
-4 |
Always rounds up |
Math.floor(x) |
4 |
4 |
-5 |
Always rounds down |
Math.trunc(x) |
4 |
4 |
-4 |
Drops decimal part |
Beyond rounding, Math includes Math.abs() for absolute distance, Math.sqrt() for square roots, and Math.sign() to inspect whether a number is positive, negative, or zero. Constants like Math.PI and Math.E provide double-precision values right out of the box.
Math Utilities ExampleYou can combine Math.min() and Math.max() to clamp user values between a minimum and maximum range, or spread an array into Math.max(...scores).
const scores = [78, 92, 64, 88];
const highest = Math.max(...scores);
const lowest = Math.min(...scores);
// Clamp a volume setting strictly between 0 and 100
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
const circleArea = Math.PI * 5 ** 2;
console.log({ highest, lowest });
console.log("Clamped 135:", clamp(135, 0, 100));
console.log("Circle area:", Number(circleArea.toFixed(2)));
Math.max(arr): Math.max([1, 5, 3]) returns NaN. Always spread the array: Math.max(...arr).Math.floor(-4.2) returns -4: Math.floor() moves down toward negative infinity (-5). Use Math.trunc(-4.2) when you only want to strip decimals.new Math(): Trying to instantiate Math throws TypeError: Math is not a constructor.Math.max() return with no arguments?Calling Math.max() with zero arguments returns -Infinity, while Math.min() with zero arguments returns Infinity.
Use Math.hypot(dx, dy) instead of Math.sqrt(dx * dx + dy * dy) because Math.hypot() avoids overflow on large numbers.
Multiply by 100, round with Math.round((num + Number.EPSILON) * 100) / 100, and keep precision predictable.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.