Question

How to Round to At Most 2 Decimal Places in JavaScript

javascriptroundingdecimal-point

Question

I want to round a number to at most two decimal places in JavaScript, but only when needed.

For example:

10
1.7777777
9.1

I want the output to be:

10
1.78
9.1

How can I do this in JavaScript?

Short Answer

By the end of this page, you will understand how to round numbers to at most two decimal places in JavaScript, why some methods add trailing zeros, and which approach is best when you want clean numeric output like 1.78 and 9.1.

Concept

In JavaScript, rounding and formatting are related but not identical.

  • Rounding changes the numeric value.
  • Formatting changes how the value is displayed.

This matters because some JavaScript methods return a number, while others return a string.

For this problem, you want:

  • numbers rounded to 2 decimal places when needed
  • no unnecessary trailing zeros

For example:

  • 1.7777777 should become 1.78
  • 9.1 should stay 9.1, not 9.10
  • 10 should stay 10

A common beginner solution is toFixed(2), but that always produces exactly 2 decimal places:

(9.1).toFixed(2) // "9.10"

That is often useful for display, but not for this requirement.

A better fit is usually rounding mathematically first:

Math.round(num * 100) / 100

This rounds to 2 decimal places and returns a number, so JavaScript does not keep unnecessary trailing zeros.

Math.round(1.7777777 * 100) / 100 // 1.78
Math.round(9.1 * 100) / 100       // 9.1
Math.round(10 * 100) / 100        // 10

This concept matters in real programming because many applications need rounded values without forced formatting, such as:

  • prices during calculations
  • API responses
  • reports and summaries
  • user-entered numeric values

One important detail: JavaScript uses floating-point numbers, so some decimal values cannot be represented exactly. That means rounding can sometimes produce surprising results, and you may need a small adjustment for edge cases.

Mental Model

Think of rounding like trimming a piece of rope.

  • If the rope is much longer than allowed, you cut it shorter.
  • If it is already short enough, you leave it alone.

For this problem, "at most 2 decimal places" means:

  • keep up to 2 digits after the decimal point
  • do not add extra digits just to make it look uniform

So:

  • 1.7777777 gets trimmed to 1.78
  • 9.1 is already short enough, so it stays 9.1
  • 10 has no decimal part, so it stays 10

The key idea is: round only when needed, and do not force display formatting unless you want fixed-width output.

Take Quiz

Syntax and Examples

The most common approach is:

const rounded = Math.round(num * 100) / 100;

Example

function roundToTwo(num) {
  return Math.round(num * 100) / 100;
}

console.log(roundToTwo(1.7777777)); // 1.78
console.log(roundToTwo(9.1));       // 9.1
console.log(roundToTwo(10));        // 10

Why this works

  • multiply by 100 to shift two decimal places
  • round to the nearest integer
  • divide by 100 to shift back

A reusable version

function roundTo(num, places) {
  const factor = 10 ** places;
  return Math.round(num * factor) / factor;
}

console.log(roundTo(1.7777777, 2)); // 1.78
console.log(roundTo(9.1, 2));       // 9.1
console.log(roundTo(10, 2));        // 10

What about toFixed(2)?

console.log((1.7777777).toFixed(2)); // "1.78"
console.log((9.1).toFixed(2));       // "9.10"
console.log((10).toFixed(2));        // "10.00"

toFixed(2):

  • rounds correctly for many cases
  • returns a string
  • always shows exactly 2 decimal places

If you convert it back to a number, trailing zeros disappear:

console.log(Number((9.1).toFixed(2))); // 9.1

That is also a valid solution in many cases:

function roundToTwo(num) {
  return Number(num.toFixed(2));
}

Step by Step Execution

Consider this code:

const num = 1.7777777;
const result = Math.round(num * 100) / 100;
console.log(result);

Step by step

  1. Start with:
num = 1.7777777
  1. Multiply by 100:
1.7777777 * 100 = 177.77777
  1. Apply Math.round():
Math.round(177.77777) = 178
  1. Divide by 100:
178 / 100 = 1.78
  1. Print the result:
1.78

Another example

const num = 9.1;
const result = Math.round(num * 100) / 100;
console.log(result);

Step by step:

  1. 9.1 * 100 = 910
  2. Math.round(910) = 910
  3. 910 / 100 = 9.1

The number stays 9.1, so no unnecessary zero is added.

Real World Use Cases

This pattern is useful whenever your program needs clean decimal values without always forcing fixed formatting.

Common use cases

  • E-commerce calculations: round discounted prices before showing them
  • Statistics dashboards: show averages like 4.2 instead of 4.20
  • Form input cleanup: normalize user-entered decimal numbers
  • API responses: send compact rounded numeric values
  • Measurement apps: display values like 12.34, 9.1, or 8

Example: product discount

function discountedPrice(price, discountPercent) {
  const finalPrice = price * (1 - discountPercent / 100);
  return Math.round(finalPrice * 100) / 100;
}

console.log(discountedPrice(19.99, 15)); // 16.99

Example: average rating

function averageRating(total, count) {
  return Math.round((total / count) * 100) / 100;
}

console.log(averageRating(46, 5)); // 9.2
Take Quiz

Real Codebase Usage

In real projects, developers usually choose between numeric rounding and display formatting depending on the goal.

1. Use numeric rounding for calculations and data

const tax = Math.round(subtotal * 0.0825 * 100) / 100;

This is common when storing or passing values through application logic.

2. Use formatting for UI display

If a UI must always show 2 decimal places, developers often use:

price.toFixed(2)

Example:

const price = 9.1;
console.log(`$${price.toFixed(2)}`); // $9.10

3. Wrap logic in utility functions

In larger codebases, teams often avoid repeating the same rounding expression.

function roundToTwo(num) {
  return Math.round(num * 100) / 100;
}

4. Validate input before rounding

function safeRoundToTwo(value) {
  const num = Number(value);
  if (!Number.isFinite(num)) {
    throw new Error("Value must be a valid number");
  }
  return Math.round(num * 100) / 100;
}

This is a common guard-clause pattern.

5. Apply rounding to arrays of values

const values = [1.7777, 9.1, 10];
const rounded = values.map(num => Math.round(num * 100) / 100);

console.log(rounded); // [1.78, 9.1, 10]

This pattern appears in reporting, analytics, and data transformation code.

Common Mistakes

1. Using toFixed(2) when you want a number

Broken expectation:

const value = (9.1).toFixed(2);
console.log(value); // "9.10"

Problem:

  • it returns a string
  • it always shows 2 decimal places

Fix:

const value = Number((9.1).toFixed(2));
console.log(value); // 9.1

2. Forgetting floating-point edge cases

This can be surprising:

console.log(Math.round(1.005 * 100) / 100); // may not give expected result

A safer pattern for some edge cases is:

function roundToTwo(num) {
  return Math.round((num + Number.EPSILON) * 100) / 100;
}

console.log(roundToTwo(1.005)); // 1.01

3. Confusing display with stored value

const price = 9.1;
console.log(price);           // 9.1
console.log(price.toFixed(2)); // "9.10"

The first is a number. The second is display formatting.

4. Rounding too early in calculations

Broken approach:

const subtotal = 10.235;
const rounded = Math.round(subtotal * 100) / 100;
const tax = rounded * 0.1;

It is often better to round at the final step:

const subtotal = 10.235;
const tax = Math.round(subtotal * 0.1 * 100) / 100;

5. Applying string methods to numbers incorrectly

Broken code:

const num = 9.1;
console.log(num.replace(/0+$/, ""));

Problem:

  • replace() is a string method, not a number method

Fix:

const formatted = num.toFixed(2).replace(/\.00$/, "").replace(/(\.\d)0$/, "$1");
console.log(formatted);

Use this only if you specifically want string formatting.

Comparisons

ApproachReturnsTrailing zerosGood forExample result for 9.1
Math.round(num * 100) / 100numberNocalculations, compact output9.1
num.toFixed(2)stringYesdisplay with exactly 2 decimals"9.10"
Number(num.toFixed(2))numberNosimple rounded numeric output9.1

Math.round(...) vs toFixed(2)

  • Use Math.round(...) when you want a number.
  • Use toFixed(2) when you want formatted text with exactly two decimals.
  • Use Number(toFixed(2)) when you want the rounding behavior of toFixed, but the final result as a number.

Which should you choose?

For this exact requirement, a strong default is:

function roundToTwo(num) {
  return Math.round((num + Number.EPSILON) * 100) / 100;
}

It keeps output numeric and avoids unnecessary zeros.

Take Quiz

Cheat Sheet

// Round to at most 2 decimal places
Math.round(num * 100) / 100

// Safer for some floating-point edge cases
Math.round((num + Number.EPSILON) * 100) / 100

// Fixed 2 decimal places as a string
num.toFixed(2)

// Rounded to 2 decimals, then converted back to number
Number(num.toFixed(2))

Quick rules

  • Math.round(...) returns a number
  • toFixed(2) returns a string
  • numbers do not preserve unnecessary trailing zeros
  • strings can preserve formatting like 9.10

Best choice for this question

function roundToTwo(num) {
  return Math.round((num + Number.EPSILON) * 100) / 100;
}

Example outputs

roundToTwo(1.7777777) // 1.78
roundToTwo(9.1)       // 9.1
roundToTwo(10)        // 10

Watch out for

  • floating-point issues like 1.005
  • using toFixed() when you need a number
  • rounding too early in multi-step calculations

FAQ

How do I round to 2 decimal places in JavaScript without trailing zeros?

Use:

Math.round((num + Number.EPSILON) * 100) / 100

This returns a number, so extra zeros are not kept.

Why does toFixed(2) return 9.10 instead of 9.1?

Because toFixed(2) is a formatting method that always shows exactly two decimal places and returns a string.

Should I use Math.round() or toFixed()?

Use Math.round() for numeric results. Use toFixed() for display formatting.

Why is rounding 1.005 sometimes incorrect in JavaScript?

Because JavaScript uses floating-point numbers, and some decimals cannot be represented exactly in binary.

How can I remove trailing zeros after toFixed(2)?

Convert the result back to a number:

Number(num.toFixed(2))

Can I round to a different number of decimal places?

Yes:

function roundTo(num, places) {
  const factor = 10 ** places;
  return Math.round(num * factor) / factor;
}

Is the result still a number after rounding with Math.round()?

Yes. Math.round(num * 100) / 100 returns a number.

Take Quiz

Mini Project

Description

Build a small utility that cleans and rounds a list of numeric values to at most two decimal places. This mirrors real tasks such as preparing prices, measurements, or API data before display or storage.

Goal

Create a function that rounds each number in an array to at most two decimal places without adding unnecessary trailing zeros.

Requirements

  • Create a function that accepts an array of numbers.
  • Round each number to at most two decimal places.
  • Return the cleaned values as numbers.
  • Demonstrate the function with values such as 10, 1.7777777, 9.1, and 1.005.
Take Quiz

Keep learning

Related questions

View more