CodeBlanks Logo Icon CodeBlanks

The Math object

JavaScript course · Beginner · Lesson 20/133

Learn rounding with Math.round, Math.floor and Math.ceil.

The Math object

In JavaScript Math is a built-in object that holds useful constants and methods for numbers. You do not create a new Math; you just use it directly.

Three common rounding methods are:

  • Math.round(x) — rounds to the nearest integer.
  • Math.floor(x) — always rounds down to an integer.
  • Math.ceil(x) — always rounds up to an integer.

For example Math.round(4.5) gives 5, Math.floor(4.9) gives 4 and Math.ceil(4.1) gives 5.

Down or up?

Math.floor and Math.ceil always go the same direction; that is why they serve different real world jobs.

When you compute remaining stock in a shop you use Math.floor: 7.8 boxes means 7 full boxes. But when you count the pages needed you use Math.ceil: even 3.1 pages means 4 pages, because you cannot print half a page.

The job, not the number, picks the rounding direction.

Exercise Round the score down and up

Declare const score = 7.8;. Then declare down with Math.floor(score) and up with Math.ceil(score). Log both with console.log.

Show example solution
const score = 7.8;
const down = Math.floor(score);
const up = Math.ceil(score);
console.log(down);
console.log(up);

Test yourself

  1. What does Math.round(4.5) return?

    console.log(Math.round(4.5));
    • 4
    • 4.5
    • 5
    • Throws an error
    Show answer

    5 — Correct. Math.round sends 0.5 and above upward; for 4.5 the result is 5.

  2. Round 9.99 to the nearest integer

    const rounded = Math.round(____);
    Show answer
    const rounded = Math.round(9.99);
  3. Match each method to its job

    Math.round
    Nearest whole number
    Math.floor
    Down to whole number
    Math.ceil
    Up to whole number
    Math.PI
    The pi constant (~3.14)
  4. What does Math.ceil(3.1) return?

    console.log(Math.ceil(3.1));
    • 3
    • 3.1
    • Throws an error
    • 4
    Show answer

    4 — Correct. Math.ceil always goes up; for 3.1 the next whole number up is 4.

All lessons in Beginner