completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

Number & Math in depth

Go deeper into JavaScript numbers: safe integers, numeric limits, exact checks, formatting, Math helpers, random-number traps, and modern precision tools.

By the end, you can
  • 01
    Know the safe zoneUse Number.EPSILON to compare decimals, check whether whole numbers are exact, and know the biggest and smallest numbers.
  • 02
    Pick the right checkKnow when to use Number.isNaN, Number.isFinite, Number.isInteger, and Number.isSafeInteger.
  • 03
    Use Math wellShow numbers as text, make fair random choices, and check that new Math tools exist before you use them.

Which numbers JavaScript can store exactly

The Numbers & math lesson showed the basics: the 0.1 + 0.2 surprise, NaN, Infinity, rounding, reading numbers from text, and the Math object. This lesson stays with the same type, number, and looks closer.

JavaScript stores every number in the same fixed amount of memory: 64 bits. That is enough for very big and very small numbers. It is not enough to store every number exactly. So JavaScript stores the nearest number it can.

Think of all the numbers JavaScript can store as marks on a long ruler:

  • Near 1, the marks are very close together.
  • Far from zero, the marks are far apart.
  • A number between two marks is moved to the nearest mark.

Most number bugs come from asking the wrong question. This lesson helps you ask the right one:

  • Is this a real, finite number?
  • Is this whole number stored exactly?
  • How should I show this number as text?
  • Is this random choice fair?
The short version

To check input, use the Number. checks, like Number.isFinite. To check that a whole number is exact, use Number.isSafeInteger. To compare two decimals, allow a tiny difference based on Number.EPSILON. To pick a fair random whole number, use Math.floor.

You will also meet two new tools, Math.sumPrecise and Math.f16round. Older browsers don't have them yet. So this page first checks whether your browser has them, and only then uses them.

Number.EPSILON and safe whole numbers

STEP THROUGH

Number.EPSILON is the gap between 1 and the next number JavaScript can store. It is about 0.0000000000000002. On the ruler, it is the space between the mark at 1 and the next mark.

It helps with decimals. 0.1 + 0.2 is not exactly 0.3, but the difference is smaller than Number.EPSILON. So you can say the two are "close enough". For bigger numbers the marks are farther apart, so you must make the allowed difference bigger too.

Whole numbers have a limit too. A whole number is safe when JavaScript can store it and every whole number below it exactly. The biggest safe whole number is Number.MAX_SAFE_INTEGER, which is 2 ** 53 - 1, or 9007199254740991. (** means "to the power of".)

Real-life analogyEPSILON is a tiny gap on a ruler

Near 1, the marks on the ruler are so close that a tiny error doesn't matter. Far from zero, the marks spread out. It is like a street: in town, every house number exists. Out on a country road, the numbers jump, and some house numbers are missing. Number.MAX_SAFE_INTEGER is the last house where no number is missing yet.

In real life: A ruler with tiny marks near 1
In JavaScript: Number.EPSILON, the gap just after 1
In real life: A street in town where every house number exists
In JavaScript: Safe whole numbers, up to Number.MAX_SAFE_INTEGER
In real life: A country road where house numbers jump
In JavaScript: Whole numbers past 2 ** 53 - 1, where some are missing

Step through the code below. Watch what happens just past the last safe whole number. A number can be whole and still not be safe.

Step past the last safe whole number
Step 0 of 5Ready
Your turn: follow the blue line

Step past the last safe whole number. Then compare a tiny decimal error with Number.EPSILON.

Running in
  1. script
Next: line 1
console.log(maxSafe + 1);console.log(maxSafe + 2);console.log(Number.isSafeInteger(maxSafe + 1));console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Two sums, maxSafe + 1 and maxSafe + 2, both give the same stored number, 9007199254740992.maxSafe + 1maxSafe + 29007199254740992two sums, one number
maxSafe is 9007199254740991. Adding 1 gives 9007199254740992. Adding 2 should give 9007199254740993, but JavaScript can't store that whole number, so it uses the nearest one it can: 9007199254740992 again.

The next code has four small checks.

Comparing decimals, and minus zeroPop out in the code editor (opens in a new tab)JavaScript
const total = 0.1 + 0.2;
console.log(total === 0.3);
console.log(Math.abs(total - 0.3) < Number.EPSILON);
console.log(Math.abs(1000000000000.1 - 1000000000000) < Number.EPSILON);
console.log(Object.is(-0, 0));

Line by line:

  • Line 1 adds 0.1 + 0.2 and keeps the result in total.
  • Line 2 asks whether total is exactly 0.3. It prints false, because the decimals are stored a tiny bit off.
  • Line 3 asks whether the difference is smaller than Number.EPSILON. It prints true.
  • Line 4 does the same for two numbers near one trillion. Their difference is about 0.1, which is far bigger than Number.EPSILON. It prints false.
  • Line 5 compares -0 and 0 with Object.is. It prints false.

Line 4 shows that Number.EPSILON alone is too small for big numbers. For big numbers, pick an allowed difference that fits your data, like one cent for prices.

JavaScript has a minus zero, -0. -0 === 0 is true, so === can't tell them apart. Object.is(a, b) checks whether two values are exactly the same, so it can.

For whole numbers past the safe limit, use BigInt

Sometimes you need exact whole numbers past the safe limit: long IDs, big counters, or exact sums. The BigInt lesson shows a separate type for that, bigint. Don't keep a huge ID in a normal number. Some of its digits can change without any warning.

The biggest number, the smallest number, and Infinity

Safe whole numbers answer one question: "Which whole numbers are stored exactly?" Two other limits answer a different question: "How big, or how close to zero, can a normal number get?"

  • Number.MAX_VALUE is the biggest number JavaScript can store. It is about 1.8e308.
  • Number.MIN_VALUE is the smallest number above zero that JavaScript can store. It is about 5e-324.

The e means "times 10 to the power of". So 1.8e308 is a whole number with 309 digits, and 5e-324 is a tiny number with 323 zeros after the decimal point before the 5.

Real-life analogyMAX_VALUE is the roof; MIN_VALUE is a thin slice

The name MIN_VALUE tricks many people. It is not the most negative number. It is the thinnest sheet you can place just above the floor, which is zero: 5e-324.

In real life: The roof of the building
In JavaScript: Number.MAX_VALUE, the biggest number JavaScript can store
In real life: A thin sheet of paper just above the floor
In JavaScript: Number.MIN_VALUE, the smallest number above zero
In real life: The floors below the ground
In JavaScript: Negative numbers, down to -Number.MAX_VALUE
In real life: Past the roof
In JavaScript: Infinity, when a result is too big

The four names below sound alike but mean different things. Each row gives the name, what it really means, and when you need it.

Four number limits that sound alike
NameWhat it really meansWhen you need it
Number.MAX_SAFE_INTEGER9007199254740991. It is the last whole number before some whole numbers go missing.You need whole numbers to be exact.
Number.MAX_VALUEThe biggest number JavaScript can store.You want to know when a result gets too big.
Number.MIN_VALUEThe smallest number above zero, 5e-324.You want to know when a result gets too close to zero to store.
Infinity / -InfinityA special number that is bigger, or smaller, than every normal number.A result was too big, or you divided by zero.

When a result is too big, JavaScript doesn't throw an error. It gives Infinity instead. Some code uses Infinity on purpose, for example as a starting value when you look for the smallest number. But for things people see, like prices, distances, or percentages, treat Infinity as wrong data.

Checking numbers: isInteger, isSafeInteger, isNaN, and isFinite

SORT

JavaScript has two sets of checks for NaN ("not a number") and for finite numbers. A finite number is a normal number: not NaN, not Infinity, and not -Infinity.

  • The old global checks, isNaN and isFinite, first change the value into a number. Then they check it.
  • The newer checks, Number.isNaN and Number.isFinite, change nothing. A value that is not a number is never NaN and never finite to them.

That one difference explains every result below.

The text "abc" goes to two checks. isNaN changes it into a number first, gets NaN, and says true. Number.isNaN does not change it, sees text, and says false."abc"trueisNaNchanges it firstfalseNumber.isNaNchanges nothing
The global isNaN first turns "abc" into a number. That gives NaN, so it says true. Number.isNaN changes nothing. Text is not the NaN value, so it says false.

The table runs all four checks on six values. Read one row at a time: the first cell is the value, and the other cells show what each check returns.

What each NaN and finite check returns
Value you checkisNaNNumber.isNaNisFiniteNumber.isFinite
"abc"truefalsefalsefalse
""falsefalsetruefalse
"42"falsefalsetruefalse
NaNtruetruefalsefalse
Infinityfalsefalsefalsefalse
nullfalsefalsetruefalse

Look at the "" row. The empty string turns into 0, so the global isFinite says true. That is how an empty form field can slip through as zero.

Use the global checks only when you want that change into a number to happen. When you check user input, change it yourself with Number(input), then use the Number. checks.

There are two checks for whole numbers too:

  • Number.isInteger(x) asks: "Is this a number with nothing after the decimal point?"
  • Number.isSafeInteger(x) asks: "Is this a whole number, and is it stored exactly?"
Global isNaN or Number.isNaN?
  • isNaN("abc")
  • isFinite("")
  • Number.isNaN("abc")
  • Number.isFinite("42")
  • Number.isInteger(4.0)
  • Number.isSafeInteger(2 ** 53)
Try it yourself
0 of 6 correct

Put each check in its group. Does it change the value into a number first, change nothing, or check for whole numbers?

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Showing numbers as text: toPrecision, toExponential, and toString

INTERACTIVE

These methods answer one question: "How should this number look as text?" Each one returns a string.

  • toPrecision(5) keeps 5 significant digits. Those are the digits that count, starting from the first digit that is not zero. (123.456).toPrecision(5) gives "123.46".
  • toExponential(2) writes the number with an e, keeping 2 digits after the decimal point. (123.456).toExponential(2) gives "1.23e+2", which means 1.23 times 10 to the power of 2.
  • toString(radix) writes the number in another base. The base, also called the radix, is how many different digits you use. We normally use base 10: the digits 0 to 9. Base 2 (binary) uses only 0 and 1. Base 16 (hexadecimal, or "hex") uses 0 to 9 and then a to f. Any base from 2 to 36 works.
Real-life analogyA base is a different kind of car dial

A car has a dial, called an odometer, that counts how far the car has gone. Imagine three cars that drove the same distance, each with a different dial. The digits look different, but the distance is the same. Binary and hex are just other ways to write the same number. They are handy when you look at colors, on/off flags, and bytes.

In real life: A dial with the digits 0 to 9
In JavaScript: 255
In real life: A dial with only 0 and 1
In JavaScript: 11111111 from (255).toString(2)
In real life: A dial with 0 to 9 and a to f
In JavaScript: ff from (255).toString(16)
The number 255 written two ways. toString(2) gives the text "11111111" in base 2. toString(16) gives the text "ff" in base 16.255"11111111"toString(2)base 2"ff"toString(16)base 16
It is the same number each time; only the digits change. Base 2 uses the digits 0 and 1. Base 16 uses 0 to 9 and then a to f. Both results are text (strings), not numbers.
Read and write numbers as textPop out in the code editor (opens in a new tab)JavaScript
console.log(parseInt("1010", 2));
console.log((255).toString(2));
console.log((1234.5).toFixed(2));
console.log((1234.5).toPrecision(4));

Line by line:

  • Line 1 reads the text "1010" as base 2. The second argument, 2, is the base. It prints 10.
  • Line 2 goes the other way. It writes 255 in base 2 and prints 11111111.
  • Line 3 keeps exactly 2 digits after the decimal point. It prints 1234.50.
  • Line 4 keeps 4 significant digits. It rounds 1234.5 to 1235.

All of these give back a string. Use them to show a number to people. Don't do more math on the result.

Now try the number inspector. Type a number or click a preset, especially 2 ** 53, 5e-324, and -0. The "number just below" and "number just above" rows show the closest numbers JavaScript can store on each side. The gap between them is the space between the marks on the ruler at that spot.

Look at one number in many ways
Questions to ask about one numberPop out in the code editor (opens in a new tab)JavaScript
const value = Number(input);Number.isInteger(value);Number.isSafeInteger(value);value.toPrecision(5);value.toExponential(2);value.toFixed(2);value.toString(2);value.toString(16);
Results123.456
Number.isIntegerfalse
Number.isSafeIntegerfalse
toPrecision(5)123.46
toExponential(2)1.23e+2
toFixed(2)123.46
toString(2)1111011.0111010010111100011010100111111011111001110111
toString(16)7b.74bc6a7ef9dc
less than EPSILON from a whole numberfalse
number just below123.45599999999999
number just above123.45600000000002
Try it yourself

123.456 is not a safe whole number. This number has a decimal part. JavaScript stores the nearest number it can.

Your browser works out every row from the number you typed. Very long base 2 and base 16 strings are cut short to fit.

Math tools: rounding, angles, logarithms, and distance

STEP THROUGH

Math is a ready-made toolbox of number functions. You don't create it with new; you just call its functions, like Math.max. This section uses four groups of tools:

  • Rounding: Math.round, Math.floor, Math.ceil, and Math.trunc.
  • Angles: Math.sin, Math.cos, and Math.atan2. This part of math is called trigonometry.
  • Logarithms: Math.log10(x) asks "10 to what power gives x?", and Math.log2(x) asks the same for 2. Math.log uses the number e (about 2.718).
  • Distance: Math.hypot(a, b) gives the length of the long side of a right triangle with sides a and b.

The angle functions don't use degrees. They use radians, another way to measure angles. 180 degrees is π radians. The code below changes degrees into radians, then calls real Math functions. At 180 degrees, Math.sin(Math.PI) gives 1.2246467991473532e-16. That is not zero, but it is very close. It happens because Math.PI is stored a tiny bit off.

Try Math tools with one angle
Step 0 of 6Ready
Your turn: follow the blue line

Change the angle, then step through real Math calls. Look at the sine at 180 degrees: it is almost 0, but not quite.

Running in
  1. script
Next: line 1
const radians = degrees * Math.PI / 180;console.log(Math.sin(radians));console.log(Math.hypot(3, 4));console.log(Math.log10(1000));console.log(Math.log2(8));
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Change line 1: the angle in degrees

A new angle starts the replay again. Only line 1 changes; the hypot and log lines stay the same.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Each rounding tool goes its own way

Each one turns a number into a whole number:

  • Math.floor always goes down, toward -Infinity.
  • Math.ceil always goes up, toward Infinity.
  • Math.trunc cuts off the part after the decimal point, so it goes toward zero.
  • Math.round goes to the nearest whole number. Exactly half, like .5, goes up, toward Infinity.
Rounding 2.5 and -2.5Pop out in the code editor (opens in a new tab)JavaScript
console.log(Math.round(2.5));
console.log(Math.round(-2.5));

Line 1 prints 3. Line 2 prints -2, not -3. Going up from -2.5 means going toward the bigger number, and -2 is bigger than -3. So Math.round does not always round away from zero.

Math.random: when random is not fair

RUN IT

Math.random() gives a random-looking number from 0 up to 1. It can be 0, but it is never 1. It is fine for games, changing how a page looks, simulations, and demos.

It is not safe for secrets. Someone could guess the numbers it makes. For tokens, passwords, or IDs that must be hard to guess, use the browser's Web Crypto tools, such as crypto.getRandomValues() or crypto.randomUUID(). The Web Crypto lesson covers them.

Two common bugs make random results unfair:

  • Math.round(Math.random() * 6) for a die roll. It can give 0, and it gives 0 and 6 only half as often as the other results.
  • array.sort(() => Math.random() - 0.5) to shuffle. sort expects its compare function to give the same answer for the same two items every time. A random answer breaks that, so some orders come up more often than others.
Each card's width shows how likely a result is. Left: Math.round(r * 6) gives 0 to 6, and 0 and 6 are half as likely as the rest. Right: Math.floor(r * 6) + 1 gives 1 to 6, all equally likely.Math.round(r * 6)01234567 results, unevenMath.floor(r * 6) + 11234566 results, equal
Here r is Math.random(). A wider card means a more likely result. Rounding gives seven results, and the two end ones get only half a share. Math.floor plus 1 gives six equal shares.

The fair way to shuffle is the Fisher–Yates shuffle. It walks from the last item to the first. For each spot, it swaps in a random item from the ones not placed yet. Every order is equally likely.

Click the button below to make real random samples in your browser. Compare the unfair and fair versions.

See unfair random results in your own run
A fair whole number and a fair shufflePop out in the code editor (opens in a new tab)JavaScript
function randomInt(min, max) {  return Math.floor(Math.random() * (max - min + 1)) + min;} function shuffle(items) {  const copy = [...items];  for (let i = copy.length - 1; i > 0; i -= 1) {    const j = Math.floor(Math.random() * (i + 1));    [copy[i], copy[j]] = [copy[j], copy[i]];  }  return copy;}
Your runnot run yet

Unfair: Math.round gives 0 to 6

00
10
20
30
40
50
60

Fair: Math.floor gives 1 to 6

10
20
30
40
50
60

Unfair shuffle: sort(() => random - 0.5)

ABC0
ACB0
BAC0
BCA0
CAB0
CBA0

Fair shuffle: Fisher–Yates

ABC0
ACB0
BAC0
BCA0
CAB0
CBA0
Try it yourself

Click the button to make real random samples in your browser. Nothing random happens until you click.

The bars show your run, made with your browser's Math.random() when you click. Don't use Math.random() for secrets.

Special Math tools: sumPrecise, fround, f16round, clz32, and imul

STEP THROUGH

Some Math tools exist for special jobs: very exact sums, or working with other systems that store numbers in fewer bits. A bit is one binary digit, 0 or 1. A normal JavaScript number uses 64 bits. These tools work with 32 bits:

  • Math.fround(x) rounds x to the nearest number that fits in 32 bits. Math.fround(5.5) stays 5.5, but Math.fround(5.05) becomes 5.050000190734863.
  • Math.clz32(x) counts the zeros at the start of x, written as 32 binary digits. Math.clz32(1) gives 31: thirty-one zeros, then a single 1.
  • Math.imul(a, b) multiplies two whole numbers the way a 32-bit system does. In that system, 0xffffffff means -1, so Math.imul(0xffffffff, 5) gives -5.

Math.sumPrecise and Math.f16round are newer, and some browsers don't have them yet. So this page waits until it is running in your browser, then checks whether they exist. It only calls them if they do.

  • Math.sumPrecise adds a list of numbers exactly. Adding [1e16, 1, -1e16] one by one gives 0: the 1 is lost. Math.sumPrecise gives 1.
  • Math.f16round rounds a number to fit in 16 bits. If your browser doesn't have it, the page only describes it.

The bitwise operators, like | and &, work on single bits. Before they start, they turn each side into a 32-bit whole number. That can change big numbers.

Bitwise operators keep only 32 bitsPop out in the code editor (opens in a new tab)JavaScript
console.log((2 ** 32 + 1) | 0);

This prints 1. 32 bits can hold only 2 ** 32 different whole numbers. Past that, the count starts again from zero. So 2 ** 32 + 1 becomes just 1. This is useful for flags and quick hash codes, but don't use it to work with big whole numbers.

Step through the special Math tools
Step 0 of 5Ready
Your turn: follow the blue line

These tools have special jobs: rounding to 32 bits, working with bits, and checking that a new Math tool exists.

Running in
  1. script
Next: line 1
console.log(Math.fround(5.05));console.log(Math.clz32(1));console.log(Math.imul(0xffffffff, 5));console.log(typeof Math.sumPrecise === "function");
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Does your browser have the newest Math tools?
Tools every browser has, and one checkPop out in the code editor (opens in a new tab)JavaScript
console.log(Math.fround(5.5));console.log(Math.fround(5.05));console.log(Math.clz32(1));console.log(Math.imul(0xffffffff, 5));console.log(typeof Math.sumPrecise === "function");
What your browser haswaiting
Adding [1e16, 1, -1e16] one by one…
Has Math.sumPrecise?…
sumPrecise resultnot in this browser
Has Math.f16round?…
f16round(1.337)rounds to 16 bits when the browser has it
For comparison5.050000190734863 is 5.05 rounded to 32 bits, not 16
Try it yourself
Checked once the page runs in your browser

Waiting for the page to start in your browser before checking.

Math.sumPrecise and Math.f16round are new. Older browsers and Node 22 may not have them.

Where you’ll use this

These tools show up in everyday web work:

  • Check form input: change it with Number(input), then use Number.isFinite. That way an empty field ("") doesn't slip through as zero.
  • Check Number.isSafeInteger(id) before you trust a number ID to be exact. Keep bigger IDs as strings or as BigInt.
  • Use toString(16) and toString(2) to look at colors, on/off flags, and bytes.
  • Use Math.hypot(dx, dy) to find how far the mouse moved, for drawing on a canvas, or to decide when a drag starts.
  • Use the Fisher–Yates shuffle for quizzes, flashcards, and playlists. Don't shuffle with a random sort.
Which tool fits the job?
  • value.toPrecision(5)
  • value.toString(16)
  • Math.ceil(price)
  • Math.floor(Math.random() * n)
  • Fisher–Yates shuffle
  • Math.imul(hash, 31)
Try it yourself
0 of 6 correct

Put each tool in the group for the job it does best.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common misconceptions

"MIN_VALUE is the most negative number."

No. It is the smallest number above zero. The most negative normal number is -Number.MAX_VALUE.

"If a number is whole, it is safe."

No. Number.isInteger(2 ** 53) is true, but Number.isSafeInteger(2 ** 53) is false. Past the safe limit, some whole numbers can't be stored.

"Number.EPSILON fixes every decimal comparison."

No. It is the gap next to 1. For bigger numbers the gaps are bigger, so the allowed difference must grow too.

"The global checks are stricter because they are shorter."

It is the other way round. isNaN and isFinite change the value into a number first. Number.isNaN and Number.isFinite change nothing, so they are stricter.

"Math.random is fair and safe for everything."

No. It is not safe for secrets, because its numbers can be guessed. And the way you turn it into a whole number can make some results more likely than others.

Practice: exact numbers and Math

5 EXERCISES
Exercise 1 · Warm-upPredict four number checks

Guess the four printed lines without running the code. Then check your answer.

Starter codePop out in the code editor (opens in a new tab)JavaScript
console.log(Number.isSafeInteger(2 ** 53));
console.log(Number.isFinite("42"));
console.log(isFinite("42"));
console.log((255).toString(16));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeWrite isAlmostEqual(a, b)

    Write a function that says two numbers are equal when they differ only by a tiny error. Test it with 0.1 + 0.2 and 0.3.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function isAlmostEqual(a, b) {
      return Math.abs(a - b) <= Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
    }
    console.log(isAlmostEqual(0.1 + 0.2, 0.3));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticePick a fair random whole number

      Complete a function that returns a whole number from min to max, with both ends included. Which rounding tool belongs in it?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      function randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeWrite the Fisher–Yates shuffle

        Write the shuffle from this lesson. One run looking mixed is not enough. The result must keep the same items, each exactly once.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        function shuffle(items) {
          const copy = [...items];
          for (let i = copy.length - 1; i > 0; i -= 1) {
            const j = Math.floor(Math.random() * (i + 1));
            [copy[i], copy[j]] = [copy[j], copy[i]];
          }
          return copy;
        }

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · PracticeWrite one number in two bases

          Use toString(radix) to print 255 in base 2 and in base 16.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const value = 255;
          console.log(value.toString(2));
          console.log(value.toString(16));

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Every code answer comes from real JavaScript output. Read the explanations for the wrong answers too.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does this line print, just past the safe limit?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2);

              Choose an answer to see the explanation.

            2. Question 2 of 7What is Number.MIN_VALUE?

              Choose an answer to see the explanation.

            3. Question 3 of 7What do the two NaN checks print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Number.isNaN("abc"));
              console.log(isNaN("abc"));

              Choose an answer to see the explanation.

            4. Question 4 of 7What does ten print in base 2?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log((10).toString(2));

              Choose an answer to see the explanation.

            5. Question 5 of 7What does the sine of Math.PI print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Math.sin(Math.PI));

              Choose an answer to see the explanation.

            6. Question 6 of 7Which line gives a fair die roll from 1 to 6?

              Choose an answer to see the explanation.

            7. Question 7 of 7What do fround, clz32, and imul print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Math.fround(5.05));
              console.log(Math.clz32(1));
              console.log(Math.imul(0xffffffff, 5));

              Choose an answer to see the explanation.

            Key takeaways

            • Number.EPSILON is the gap next to 1. When you compare bigger numbers, make the allowed difference bigger too.
            • Number.MAX_SAFE_INTEGER is about whole numbers being exact. Number.MAX_VALUE and Number.MIN_VALUE are about how big, or how close to zero, a number can get.
            • Use the Number. checks. Use the global checks only when you want the value changed into a number first.
            • toPrecision, toExponential, and toString(radix) write the same number as text in different ways.
            • Math.random() is not safe for secrets. Round its result the wrong way and some results come up more often.
            • Check that new tools like Math.sumPrecise and Math.f16round exist before you call them.

            Remember the one-liner.
            JavaScript numbers are marks on a long ruler with gaps: know the gap, check the limits, and pick the right Math tool.

            Up next: Internationalization with Intl. It shows numbers the way people in each country expect: money, languages, and units.

            CompleteFrontend Clear concepts. Working examples.