Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 5 of 58

Numbers and the Math object

Work with numbers in JavaScript, understand 0.1 + 0.2, NaN and Infinity, round and format values, and use the Math object for min, max and random.

13 minGetting startedUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonDo arithmetic safely, round and format numbers for display, parse text into numbers, and use Math for common jobs such as random values.

After this lesson you can calculate with numbers, avoid the classic decimal surprise, turn text into numbers, round values for display, and use the built-in Math object.

One kind of number

Unlike many languages, JavaScript has a single number type for 5 and 5.25 alike. You write them directly in your code.

javascript
console.log(1_000_000);   // 1000000, underscores are only for readability
console.log(Number.isInteger(5.0));   // true

Arithmetic uses the operators you know: +, -, *, /, plus % (remainder) and ** (power). The Operators lesson covers them in detail. Here we focus on how numbers behave.

The 0.1 + 0.2 surprise

javascript
console.log(0.1 + 0.2);          // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);  // false

This is not a JavaScript bug. Computers store numbers in binary, and some decimal fractions, like one tenth, have no exact binary form, just as one third has no exact decimal form. Almost every language shows the same result.

What to do about it:

  • For display, round: (0.1 + 0.2).toFixed(2) gives "0.30".
  • For comparison, check that the difference is tiny: Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON is true.
  • For money, work in the smallest unit, such as whole cents or paise, as integers, and convert to a decimal only when showing the value.

Note that toFixed returns a string, not a number.

NaN and Infinity

Some calculations have no sensible numeric answer.

javascript
console.log(0 / 0);     // NaN
console.log(1 / 0);     // Infinity
console.log(-1 / 0);    // -Infinity
console.log(Number("abc"));   // NaN

NaN stands for "not a number". It is, confusingly, of type number. It spreads: any calculation that includes NaN gives NaN. And it is the only value not equal to itself.

javascript
console.log(NaN === NaN);          // false
console.log(Number.isNaN(NaN));    // true
console.log(Number.isNaN("abc"));  // false
console.log(isNaN("abc"));         // true  (the old global converts first)

Prefer Number.isNaN. The older global isNaN first converts its argument to a number, so it calls the text "abc" "not a number" in a way that can mislead.

Turning text into numbers

Data from forms and the page arrives as text. Convert it before doing sums.

javascript
console.log(Number("42"));       // 42
console.log(Number(""));         // 0
console.log(Number("42px"));     // NaN
console.log(parseInt("42px"));   // 42
console.log(parseFloat("3.5kg")); // 3.5
console.log(parseInt("px42"));   // NaN
  • Number(text) is strict: the whole text must be a valid number, or you get NaN. An empty string gives 0, which surprises people.
  • parseInt(text) and parseFloat(text) read as much as they can from the start and ignore the rest.

When you want a whole number from user input, Number(text) plus a check for NaN is usually the safer route, because it does not silently accept "42px".

Rounding

There are four common ways to turn a decimal into a whole number, and they differ most for negatives.

javascript
console.log(Math.round(2.5), Math.round(-2.5), Math.round(2.4));  // 3 -2 2
console.log(Math.floor(-2.5), Math.ceil(2.1), Math.trunc(-2.9));  // -3 3 -2
Method Meaning
Math.round(x) Nearest whole number. A .5 goes towards positive infinity
Math.floor(x) Down, towards negative infinity
Math.ceil(x) Up, towards positive infinity
Math.trunc(x) Cut off the decimals, towards zero

To round to decimal places, use toFixed(2) for display, or Math.round(x * 100) / 100 to keep a number.

The Math object

Math is a built-in object with useful values and functions. You never create it; you just use it.

javascript
console.log(Math.max(3, 9, 2));        // 9
console.log(Math.min(3, 9, 2));        // 2
console.log(Math.max(...[4, 8, 1]));   // 8   (spread a list into arguments)
console.log(Math.sqrt(81));            // 9
console.log(2 ** 10, Math.pow(2, 10)); // 1024 1024
console.log(Math.PI);                  // 3.141592653589793
console.log(Math.abs(-7));             // 7

Math.max() with no arguments returns -Infinity, and Math.min() returns Infinity. Those are the natural "starting values" for those functions.

Random numbers

Math.random() returns a decimal from 0 up to, but never including, 1. Scale and floor it to get a range.

html
<button id="roll">Roll a die</button>
<p id="result">Press the button.</p>
<script>
  function rollDie() {
    return Math.floor(Math.random() * 6) + 1;   // 1 to 6
  }
  document.getElementById("roll").addEventListener("click", function () {
    document.getElementById("result").textContent = "You rolled " + rollDie();
  });
</script>

The recipe for whole numbers from min to max, both included, is Math.floor(Math.random() * (max - min + 1)) + min. Math.random is fine for games and shuffling, but it is not secure, so never use it for passwords or tokens.

Formatting for people

toLocaleString formats a number using local conventions, such as thousands separators.

javascript
console.log((1234567.891).toLocaleString("en-US"));  // 1,234,567.891
console.log((1234567.891).toLocaleString("en-IN"));  // 12,34,567.891

Results depend on the locale data available in the environment, so check them on your target browsers. Number conversion to other bases also exists, for example (255).toString(16) gives "ff".

Common mistakes

  • Comparing decimals with ===. Round them first or compare with a tolerance.
  • Adding numbers that are really strings. "5" + 3 is "53". Convert with Number() first.
  • Using x === NaN. It is always false. Use Number.isNaN(x).
  • Forgetting toFixed returns text. Convert back with Number(...) if you need to calculate more.
  • Off-by-one in dice rolls. Without the + 1, your die shows 0 to 5.
  • Doing money in decimals. Store whole cents as integers.

Exercise

  1. Calculate a total of 19.99 * 3 and print it raw, then with toFixed(2).
  2. Write a snippet that picks a random whole number between 10 and 20, inclusive. Run it several times.
  3. Convert the text "250" to a number, add 50, and print the result.
  4. Check what Math.round(-0.5) and Math.floor(-0.5) give, and explain the difference in a comment.

Next: Strings. For a ready-made calculator to test your results against, try the percentage calculator.

Key points

  • JavaScript has one number type for whole numbers and decimals, stored as floating point.
  • Decimal fractions are not always exact, so 0.1 + 0.2 gives 0.30000000000000004. Round for display with toFixed.
  • NaN means "not a number", is not equal to itself, and is detected with Number.isNaN.
  • Math.round, floor, ceil and trunc round in different ways, especially for negative numbers.
  • Math.random gives a number from 0 up to but not including 1, which you scale to get dice rolls and similar values.

Check yourself

1. What does 0.1 + 0.2 === 0.3 give?
2. What does Math.floor(-2.5) return?
3. How do you correctly test whether a value is NaN?
4. Which expression gives a whole number from 1 to 6, each equally likely?
5. What does parseInt("42px") return?

Free tools for this lesson