← Back to Home

JavaScript: How to Round a Number

Complete guide to rounding numbers in JavaScript

JavaScript Rounding Methods

JavaScript provides four built-in Math methods for rounding numbers, each with specific use cases.

Math.round()

Standard rounding (5+ up)

Math.round(4.7) → 5

Math.ceil()

Always rounds UP

Math.ceil(4.1) → 5

Math.floor()

Always rounds DOWN

Math.floor(4.9) → 4

Math.trunc()

Removes decimals

Math.trunc(4.9) → 4

Method 1: Math.round() - Standard Rounding

Rounds to the nearest integer using standard rules (0.5 and above rounds up).

Math.round(4.2); // 4

Math.round(4.5); // 5

Math.round(4.7); // 5

Math.round(-4.5); // -4

Method 2: Round to Decimal Places

JavaScript doesn't have built-in decimal place rounding, but we can use this technique:

// Round to 2 decimal places

function roundToTwo(num) {

return Math.round(num * 100) / 100;

}

roundToTwo(3.14159); // 3.14

roundToTwo(12.567); // 12.57

// Generic function for any decimal places

function roundToDecimals(num, decimals) {

const multiplier = 10 ** decimals;

return Math.round(num * multiplier) / multiplier;

}

roundToDecimals(3.14159, 3); // 3.142

Method 3: Math.ceil() - Always Round Up

Math.ceil(4.1); // 5

Math.ceil(4.5); // 5

Math.ceil(4.9); // 5

Use for: Inventory calculations, package quantities, staffing needs

Method 4: Math.floor() - Always Round Down

Math.floor(4.1); // 4

Math.floor(4.5); // 4

Math.floor(4.9); // 4

Use for: Age calculations, page numbers, completed units

Method 5: toFixed() - Format as String

const num = 3.14159;

num.toFixed(2); // "3.14" (string)

// Convert back to number

parseFloat(num.toFixed(2)); // 3.14 (number)

⚠️ Note: toFixed() returns a STRING, not a number. Use parseFloat() if you need a number.

Complete Examples

// Example 1: Shopping cart total

const price = 19.99;

const tax = 0.0875;

const total = Math.round((price * (1 + tax)) * 100) / 100;

console.log(total); // 21.74

// Example 2: Calculate boxes needed

const items = 47.3;

const boxesNeeded = Math.ceil(items);

console.log(boxesNeeded); // 48

// Example 3: Calculate age from years

const years = 25.9;

const age = Math.floor(years);

console.log(age); // 25

Comparison Table

ValueMath.round()Math.ceil()Math.floor()Math.trunc()
4.24544
4.55544
4.95544

Quick Reference

📌 Standard Round

Math.round(num)

⬆️ Round Up

Math.ceil(num)

⬇️ Round Down

Math.floor(num)

💰 2 Decimals

Math.round(n*100)/100