JavaScript

Numbers & Math

JavaScript has one Number type for both whole numbers and decimals. Basic arithmetic (+ - * /) works as expected, but the built-in Math object adds many more useful tools. Math.round(4.6) rounds to the nearest whole number (5). Math.floor(4.9) always rounds down (4). Math.ceil(4.1) always rounds up (5). Math.max(3, 7, 2) returns the largest value (7); Math.min(3, 7, 2) returns the smallest (2). Math.random() returns a random decimal between 0 (inclusive) and 1 (exclusive). To get a random whole number in a specific range, it's commonly combined with Math.floor(): Math.floor(Math.random() * 10) gives a random whole number from 0 to 9. parseInt("42") and parseFloat("3.14") convert text that looks like a number into an actual Number useful when a value comes from user input, which is always text by default, covered properly in the forms-related JavaScript topics later.

Why this matters

  • ·The Math object provides ready-made tools for rounding, finding extremes, and generating randomness.
  • ·Math.random() combined with Math.floor() is the standard pattern for random whole numbers.
  • ·parseInt/parseFloat safely convert text input into real numbers for calculation.

Common mistakes

  • ·Math.random() alone returns a decimal between 0 and 1 it needs extra math to become a useful random integer.
  • ·Forgetting parseInt/parseFloat on text input can cause + to join text instead of adding numbers.
  • ·Math.floor always rounds down, even for 4.99 it's easy to expect normal rounding by mistake.
Your codeHTML
Live preview

Frequently asked questions

Math.round rounds to the nearest whole number, while Math.floor always rounds down, no matter how close the decimal is to the next whole number.

Practice questions

Question 1

Use Math.max to find the largest of three numbers of your choice, and display it.

Your codeHTML
Live preview

Question 2

Generate and display a random whole number between 1 and 100.

Your codeHTML
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 3

What does Math.floor(4.9) return?