How to round a number in JavaScript
Rounding numbers is essential for displaying prices, calculating percentages, formatting measurements, and implementing features like currency conversion or statistical calculations in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented number rounding extensively in components like pricing displays, progress indicators, and data visualization where precise numeric formatting enhances user experience and data accuracy.
From my extensive expertise, the most versatile solution is using Math.round()
for basic rounding, combined with multiplication and division for decimal precision control.
This approach provides complete control over rounding behavior and handles various precision requirements efficiently.
Use Math.round()
to round a number to the nearest integer or specific decimal places.
const number = 3.7456
const rounded = Math.round(number)
// Result: 4
const roundedToTwo = Math.round(number * 100) / 100
// Result: 3.75
The Math.round()
function rounds a number to the nearest integer using standard mathematical rounding (0.5 rounds up). In the first example, Math.round(3.7456)
returns 4
because 3.7456 is closer to 4 than to 3. For decimal precision, multiply by a power of 10, round, then divide: Math.round(3.7456 * 100) / 100
gives 3.75
, rounding to 2 decimal places. The multiplication shifts the decimal point right, rounding operates on the integer, then division shifts it back to the desired precision.
Best Practice Note:
This is the same approach we use in CoreUI components for formatting currency values, progress percentages, and measurement displays across our component library.
For consistent decimal rounding, use Number(number.toFixed(2))
which handles floating-point precision issues better. For rounding down use Math.floor()
, for rounding up use Math.ceil()
. Consider using Intl.NumberFormat
for locale-aware number formatting in international applications.