Lesson

JS Math

10 min reading
Free Course

JavaScript Math: Rounding, Clamping, and Constants

The 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().

Comparing the Four Rounding Methods

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.

Practical Math Utilities Example

You 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)));

Common Mistakes to Avoid

  • Passing an array directly to Math.max(arr): Math.max([1, 5, 3]) returns NaN. Always spread the array: Math.max(...arr).
  • Assuming 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.
  • Calling new Math(): Trying to instantiate Math throws TypeError: Math is not a constructor.

Frequently Asked Questions

What does Math.max() return with no arguments?

Calling Math.max() with zero arguments returns -Infinity, while Math.min() with zero arguments returns Infinity.

How do I calculate distance or hypotenuse cleanly?

Use Math.hypot(dx, dy) instead of Math.sqrt(dx * dx + dy * dy) because Math.hypot() avoids overflow on large numbers.

How do I round a float to 2 decimal places as a number?

Multiply by 100, round with Math.round((num + Number.EPSILON) * 100) / 100, and keep precision predictable.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum