Academic Block

Math & Number Get Certified

JavaScript has one numeric type under the hood, but two built-in objects for working with it: Math, a collection of constants and functions for calculations, and Number, which provides ways to check, convert, and format individual numeric values.

Common Math Methods

Math is not a constructor — you never write new Math(). It’s simply an object holding constants and static functions you call directly.

What this code does: This example demonstrates common Math features: absolute values, powers, square roots, minimum and maximum values, random numbers, and the Math.PI constant.

console.log("Absolute value of -7:", Math.abs(-7));
console.log("2 to the power of 10:", Math.pow(2, 10));
console.log("Same thing with **:", 2 ** 10);
console.log("Square root of 144:", Math.sqrt(144));
console.log("Largest of 4, 9, 2:", Math.max(4, 9, 2));
console.log("Smallest of 4, 9, 2:", Math.min(4, 9, 2));
console.log("A random number between 0 and 1:", Math.random());
console.log("Value of pi:", Math.PI);

Math.max() and Math.min() take individual arguments, not an array. To use them with an array, spread it first: Math.max(...numbers).

Rounding Numbers

JavaScript offers several rounding methods, each behaving differently — knowing which one to reach for avoids off-by-one surprises.

What this code does: This example compares JavaScript rounding methods. Math.round() rounds to the nearest integer, while Math.floor(), Math.ceil(), and Math.trunc() follow different rules, especially for negative numbers.

console.log("Math.round(4.5):", Math.round(4.5));
console.log("Math.round(4.4):", Math.round(4.4));
console.log("Math.floor(4.9):", Math.floor(4.9));
console.log("Math.ceil(4.1):", Math.ceil(4.1));
console.log("Math.trunc(4.9):", Math.trunc(4.9));
console.log("Math.trunc(-4.9):", Math.trunc(-4.9));
console.log("Math.floor(-4.1):", Math.floor(-4.1));

Math.trunc() simply chops off the decimal part (toward zero), while Math.floor() always rounds down — for negative numbers these two give different results.

Formatting Numbers for Display

toFixed() controls decimal places for display, and toLocaleString() adds locale-aware formatting like thousands separators and currency symbols.

What this code does: This example formats numbers for display. toFixed() controls decimal places, while toLocaleString() can add separators and format values as currency or percentages.

const price = 19.9;
console.log("toFixed(2):", price.toFixed(2));

const bigNumber = 1234567.891;
console.log("toLocaleString():", bigNumber.toLocaleString("en-US"));

console.log("As currency:", bigNumber.toLocaleString("en-US", {
    style: "currency",
    currency: "USD"
}));

console.log("As a percentage:", (0.4567).toLocaleString("en-US", {
    style: "percent",
    minimumFractionDigits: 1
}));

Note that toFixed() returns a string, not a number. If you need to keep doing math with the result, convert it back with Number() or parseFloat() first.

Checking and Converting Numbers

Number provides safe ways to check whether a value is really a valid number, and to convert user input (usually strings) into numbers.

What this code does: This example converts strings to numbers and checks numeric values. It shows how Number(), parseInt(), and parseFloat() behave, along with isNaN(), Number.isInteger(), and Number.isFinite().

console.log("Number('42'):", Number("42"));
console.log("Number('abc'):", Number("abc"));
console.log("parseInt('42px'):", parseInt("42px"));
console.log("parseFloat('3.14 meters'):", parseFloat("3.14 meters"));

console.log("isNaN(NaN):", isNaN(NaN));
console.log("Number.isInteger(5):", Number.isInteger(5));
console.log("Number.isInteger(5.5):", Number.isInteger(5.5));
console.log("Number.isFinite(Infinity):", Number.isFinite(Infinity));
console.log("Is '42abc' a valid number?", Number.isNaN(Number("42abc")));

parseInt() / parseFloat() read a number from the start of a string and ignore anything trailing, while Number() requires the entire string to be numeric.

Floating-Point Quirks

JavaScript stores all numbers as 64-bit floating point, which means some decimal values can’t be represented exactly — a well-known source of confusing bugs.

What this code does: This example shows why decimal calculations can produce small floating-point errors. It demonstrates comparing values with a tolerance and using integer cents for more reliable money calculations.

console.log("0.1 + 0.2 =", 0.1 + 0.2);
console.log("Is 0.1 + 0.2 === 0.3?", 0.1 + 0.2 === 0.3);

// Fix: round to a fixed number of decimal places before comparing
function roughlyEqual(a, b, epsilon = 0.0001) {
    return Math.abs(a - b) < epsilon;
}
console.log("Roughly equal instead:", roughlyEqual(0.1 + 0.2, 0.3));

// Fix: work in integer cents instead of fractional dollars
const priceInCents = 1050;
const taxInCents = Math.round(priceInCents * 0.08);
console.log("Total in cents:", priceInCents + taxInCents);
console.log("Formatted as dollars:", ((priceInCents + taxInCents) / 100).toFixed(2));

For money in particular, a common trick is to do all the math in whole integer cents (or the smallest currency unit) and only convert to a decimal amount at the very end, for display.

Quick Reference

Method Purpose Returns
Math.round(n) Round to nearest integer Number
Math.floor(n) / Math.ceil(n) Round down / round up Number
n.toFixed(digits) Fixed decimal places, for display String
n.toLocaleString() Locale-aware formatting String
Number(str) Strict conversion of a whole string Number or NaN
parseInt(str) / parseFloat(str) Convert leading numeric part of a string Number or NaN
Number.isInteger(n) Check for a whole number Boolean

Common Mistakes

  • Comparing floating-point results directly with ===
  • Forgetting that toFixed() returns a string
  • Using parseInt() without a radix, or expecting it to reject trailing characters
  • Passing an array to Math.max() / Math.min() without spreading it
  • Doing financial calculations in fractional dollars without accounting for floating-point errors

Best Practices

  • Prefer Number.isInteger() and Number.isFinite() over the older global versions
  • For money, work in whole integer units (cents) internally
  • Use toLocaleString() for anything shown to a user
  • When comparing floating-point results, use a small tolerance
  • Convert user input explicitly and check the result

Quick Summary

  • Math provides constants and static functions for calculations
  • Math.round(), Math.floor(), Math.ceil(), and Math.trunc() all round differently
  • toFixed() and toLocaleString() are the main tools for formatting numbers
  • Number(), parseInt(), and parseFloat() convert strings to numbers with different strictness
  • Floating-point arithmetic isn’t always exact — avoid strict equality on computed decimals

Try It Yourself

What this code does: This practical example calculates a shopping cart subtotal, tax, and total, rounds the results to two decimal places, formats them as currency, and finds the highest item price.

function calculateTotal(prices, taxRate) {
    const subtotal = prices.reduce((sum, price) => sum + price, 0);
    const tax = subtotal * taxRate;
    const total = subtotal + tax;
    return {
        subtotal: Number(subtotal.toFixed(2)),
        tax: Number(tax.toFixed(2)),
        total: Number(total.toFixed(2))
    };
}

const cartPrices = [19.99, 5.5, 12.25, 3.99];
const result = calculateTotal(cartPrices, 0.08);

console.log("Subtotal:", result.subtotal.toLocaleString("en-US", { style: "currency", currency: "USD" }));
console.log("Tax:", result.tax.toLocaleString("en-US", { style: "currency", currency: "USD" }));
console.log("Total:", result.total.toLocaleString("en-US", { style: "currency", currency: "USD" }));
console.log("Highest single item:", Math.max(...cartPrices));
Tip: If a number is about to be shown to a person, reach for toLocaleString(); if it’s about to be compared or computed further, keep it a real number and round only at the very end.

🧪 Test Your JavaScript Code

Edit the code on the left and click "Run Code" to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click "Run Code" to see the output here.

Ctrl + Enter to run code Esc to close