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.7777777should become1.789.1should stay9.1, not9.1010should stay10
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:
.(num * ) /
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.7777777gets trimmed to1.789.1is already short enough, so it stays9.110has no decimal part, so it stays10
The key idea is: round only when needed, and do not force display formatting unless you want fixed-width output.
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
100to shift two decimal places - round to the nearest integer
- divide by
100to shift back
A reusable version
Step by Step Execution
Consider this code:
const num = 1.7777777;
const result = Math.round(num * 100) / 100;
console.log(result);
Step by step
- Start with:
num = 1.7777777
- Multiply by
100:
1.7777777 * 100 = 177.77777
- Apply
Math.round():
Math.round(177.77777) = 178
- Divide by
100:
178 / 100 =
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.2instead of4.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, or8
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
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 .(num * ) / ;
}
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:
Comparisons
| Approach | Returns | Trailing zeros | Good for | Example result for 9.1 |
|---|---|---|---|---|
Math.round(num * 100) / 100 | number | No | calculations, compact output | 9.1 |
num.toFixed(2) | string | Yes | display with exactly 2 decimals | "9.10" |
Number(num.toFixed(2)) | number | No | simple rounded numeric output | 9.1 |
vs
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 numbertoFixed(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) * ) / ;
}
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:
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, and1.005.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.