Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 156 ยท Data Types

Numbers

Work with JavaScript numbers - integers and decimals, why 0.1 + 0.2 is not 0.3, NaN and Infinity, toFixed, parsing text into numbers and numeric separators.

Numbers are everywhere in programs: prices, scores, coordinates, ages, percentages. JavaScript keeps things simple with a single number type for all of them. Whole numbers and decimals, positive and negative, big and small: they're all the same type.

That simplicity comes with a few surprises, such as 0.1 + 0.2 not being exactly 0.3, and a special value called NaN that isn't equal to itself. In this lesson you'll learn how numbers work, how to avoid their classic pitfalls, how to format them for display, and how to turn text into numbers safely.

Writing numbers

You write numbers directly in your code, without quotes. These are called number literals:

JavaScript
const age = 34;              // an integer
const temperature = -4.5;    // a negative decimal
const half = .5;             // same as 0.5 (but write 0.5: it's clearer)
const distanceToSun = 1.496e8;  // exponent notation: 1.496 ร— 10โธ
const tiny = 2e-6;           // 0.000002

You can also write integers in other bases, which is handy for colors, file permissions and bit flags:

JavaScript
const hex = 0xff;        // hexadecimal: 255
const binary = 0b1010;   // binary: 10
const octal = 0o17;      // octal: 15

Numeric separators

Long numbers are hard to read: is 1000000000 a million or a billion? You can put underscores between digits to group them. The underscores are only for humans; JavaScript ignores them. This feature arrived in ES2021 and works in all modern browsers and Node.js.

JS Number literals

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Separators only work in code. Text such as "1_000" won't convert to a number, as you'll see in the parsing section.

Integers and decimals are the same type

Under the hood, every JavaScript number is a 64-bit floating-point number (the IEEE 754 "double" format, used by many languages). There is no separate integer type, so 5 and 5.0 are exactly the same value:

JavaScript
console.log(5 === 5.0);   // true
console.log(7 / 2);       // 3.5, not 3: division never drops the decimals

To check whether a number happens to be whole, use Number.isInteger():

JavaScript
Number.isInteger(10);     // true
Number.isInteger(10.5);   // false
Number.isInteger("10");   // false: a string is not a number

Safe integers

A double can store integers exactly only up to a limit: Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991 (about 9 quadrillion). Beyond that, some integers can't be represented and JavaScript silently rounds them. That's plenty for counting things, but not for very large IDs or exact big-number math, where you'd use BigInt instead. Number.isSafeInteger() checks whether a value is in the safe range.

Why 0.1 + 0.2 isn't 0.3

Try this in any language that uses floating-point numbers, and you'll get the same "wrong" answer:

JS Floating-point surprises

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Computers store numbers in binary. Just as 1/3 can't be written exactly in decimal (0.3333...), 0.1 can't be written exactly in binary. JavaScript stores the closest value it can, and the tiny errors become visible when you add such values together.

This isn't a JavaScript bug, and usually it doesn't matter. When it does, use one of the fixes above:

  • Compare with a tolerance instead of === when checking decimal results. Number.EPSILON is a tiny number (about 2.2 ร— 10โปยนโถ) that works as a tolerance for values around 1; for larger values, choose a tolerance that fits your data, such as 0.001.
  • Store money in cents (or the smallest unit of the currency) as integers, and only divide by 100 when displaying. Integers within the safe range are always exact.
  • Round for display with toFixed() or Intl.NumberFormat.

NaN: Not a Number

When a calculation can't produce a meaningful number, JavaScript doesn't throw an error. It returns the special value NaN, short for "Not a Number". Despite the name, its type is number.

You get NaN from things like 0 / 0, Math.sqrt(-1), Number("hello"), or doing math with undefined. Worse, NaN is contagious: any calculation involving NaN also produces NaN, so one bad value can spread silently through a program.

NaN has one more strange property: it isn't equal to anything, not even itself. So you can't check for it with ===:

JS Detecting NaN

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use Number.isNaN(). The older global isNaN() first converts its argument to a number, so it reports true for any text that isn't numeric, which is rarely what you mean.

Infinity

Numbers that are too large to store become Infinity, and there's also -Infinity. Unlike many languages, dividing by zero in JavaScript doesn't crash; it gives Infinity (or -Infinity for a negative number divided by zero):

JavaScript
console.log(1 / 0);              // Infinity
console.log(-5 / 0);             // -Infinity
console.log(2 ** 1024);          // Infinity: too big
console.log(Number.MAX_VALUE);   // 1.7976931348623157e+308, the largest number
console.log(Number.isFinite(1 / 0));  // false

Number.isFinite(value) is a convenient all-in-one check: it returns true only for real, finite numbers, so it rules out NaN, Infinity and non-numbers in one go. It's a great way to validate numeric input.

Formatting numbers

Numbers have a few methods that return them as strings formatted for display:

  • toFixed(digits) โ€” rounds to a fixed number of decimal places.
  • toPrecision(digits) โ€” rounds to a number of significant digits.
  • toString(base) โ€” converts to text in another base, such as 2 or 16.
JS toFixed, toPrecision and toString

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two things to remember about toFixed(). First, it returns a string, so rounded + 1 joins text. Convert back with Number() if you need to keep calculating. Second, because 1.005 is really stored as 1.00499999..., it rounds down. For money, keep amounts in cents, or use Intl.NumberFormat, which also adds thousands separators and currency symbols for any locale.

To call a method directly on a number literal, wrap it in parentheses, as in (5).toFixed(2). Without them, 5.toFixed(2) is a syntax error, because the dot is read as a decimal point.

Turning text into numbers

Text from forms, URLs and files always arrives as strings. JavaScript has three main ways to turn a string into a number, and they behave differently:

  • Number(text) converts the whole string. If any part isn't numeric, the result is NaN. Leading and trailing spaces are ignored, and an empty string becomes 0.
  • parseFloat(text) reads a number from the start of the string and stops at the first character that doesn't fit, so "12.5kg" gives 12.5.
  • parseInt(text, radix) does the same but only reads a whole number. Always pass the base (the radix), usually 10.
JS Number, parseInt and parseFloat

Press Run (or Ctrl + Enter) to see the console output here.

No output.

As a rule of thumb, use Number() when the whole string should be a number, such as a form field for a quantity: it rejects junk instead of silently accepting part of it. Use parseInt() or parseFloat() when you deliberately want to read a number off the front of a string, like "300px". Always check the result with Number.isNaN() or Number.isFinite() before using it. Also watch out for empty input: Number("") is 0, which may hide a field the user left blank.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 0.1 + 0.2 === 0.3 evaluate to?

    0.1 and 0.2 can't be stored exactly in binary, so their sum is 0.30000000000000004. Compare with a tolerance or work in whole units instead.
  2. 2. How should you check whether result is NaN?

    NaN is not equal to anything, including itself, and its type is "number". Number.isNaN() is the reliable check.
  3. 3. What is (4.2).toFixed(2)?

    toFixed() always returns a string, padded with zeros to the requested number of decimals.
  4. 4. Which call returns NaN?

    Number() converts the whole string and fails if any part isn't numeric. parseInt() reads 25 from the start and stops at "px".
  5. 5. What does 10 / 0 produce in JavaScript?

    Dividing a positive number by zero gives Infinity. Only 0 / 0 gives NaN.

Summary

  • JavaScript has one number type for integers and decimals, stored as 64-bit floating-point values. Integers are exact up to Number.MAX_SAFE_INTEGER.
  • Write large numbers with numeric separators (1_000_000), and other bases with 0x, 0b and 0o.
  • Decimal math can be slightly off (0.1 + 0.2). Compare with a tolerance, use whole units like cents, and round only for display.
  • NaN means a failed calculation, spreads through math and isn't equal to itself: check with Number.isNaN(). Division by zero gives Infinity. Number.isFinite() checks for a usable number.
  • toFixed(), toPrecision() and toString(base) format numbers as strings.
  • Number() converts a whole string; parseInt(text, 10) and parseFloat() read a number from the start of one.

Next: The Math Object โ€” rounding, random numbers, powers and roots.