Skip to content

JavaScript Tutorial Numbers and Math

JavaScript Math.round, floor, ceil and trunc

Lesson 38 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

The Math object has four ways to turn a decimal into a whole number. They behave differently, especially with negative numbers.

MethodRule
Math.round(x)Nearest integer (.5 goes up)
Math.floor(x)Down, toward negative infinity
Math.ceil(x)Up, toward positive infinity
Math.trunc(x)Cut off the decimals
script.js
JS
console.log(Math.round(4.5));  // → 5
console.log(Math.round(4.4));  // → 4
console.log(Math.floor(4.9));  // → 4
console.log(Math.ceil(4.1));   // → 5
console.log(Math.trunc(4.9));  // → 4

Negative numbers

This is where they differ.

script.js
JS
console.log(Math.round(-4.5));  // → -4
console.log(Math.floor(-4.1));  // → -5
console.log(Math.ceil(-4.9));   // → -4
console.log(Math.trunc(-4.9));  // → -4

floor always goes down (more negative), while trunc simply drops the decimals. Math.round(-4.5) is -4, because .5 rounds toward positive infinity.

Rounding to decimals

Math.round rounds to whole numbers only. To keep two decimals, multiply, round, divide, or use toFixed() for display.

script.js
JS
const value = 3.14159;

console.log(Math.round(value * 100) / 100); // → 3.14
console.log(value.toFixed(2));              // → 3.14   (a string)

Typical uses

script.js
JS
// How many pages for 23 items at 10 per page? (always round up)
console.log(Math.ceil(23 / 10)); // → 3

// Which row does item index 7 belong to, with 3 per row?
console.log(Math.floor(7 / 3));  // → 2

// Round a percentage
const done = 7, total = 9;
console.log(Math.round((done / total) * 100) + "%"); // → 78%
lightbulb
Pick by intent
Number of pages needed: ceil. Whole units that fit: floor. Nearest value: round. Drop decimals regardless of sign: trunc.