Explain Codes LogoExplain Codes Logo

How can I round a number in JavaScript? .toFixed() returns a string?

javascript
number-rounding
math-functions
javascript-tricks
Alex KataevbyAlex Kataev·Dec 21, 2024
TLDR

Looking to round a number and keep it numeric? Focus your eyes on Math.round() :

let roundedNumber = Math.round(yourNumber * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);

Let's get practical and try this to round 2.345 to two decimal places:

let keyRoundedNumber = Math.round(2.345 * 100) / 100; // Well, hello there, 2.35!

This way, you receive a precise number as the output, with no string in sight.

Decoding numbers: Your cheat sheet to rounding

Get a hold of this. The task of rounding numbers in JavaScript contains various nooks and corners. Let's step by step decode them.

Integer rounding: Keeping it simple

In simple cases when you need an integer rounded:

let cleanInteger = Math.round(yourNumber); // Round and round to the nearest integer

Quick conversion: Taking the smart route

Who says you can't convert .toFixed() string back to a number? This disagrees:

let fitNumber = +yourNumber.toFixed(2); // Try the unary plus trick

And also this:

let transformedNumber = Number(yourNumber.toFixed(2)); // Or just play it cool with the Number constructor

Precise rounding: The perfectionist's guide

Beware of the daring enemy - floating point limitations. But we got it covered with Math.pow() combined with parseFloat():

let shrewdlyRounded = parseFloat((yourNumber * Math.pow(10, decimalPlaces) / Math.pow(10, decimalPlaces)).toFixed(decimalPlaces)); // Phew, we got it right!

Advanced user's guide to rounding

Let's round up our knowledge on rounding numbers.

Facing the edge cases

Pay attention to edge cases like rounding .5:

Math.round(0.5); // Returns 1, is happy Math.floor(0.5); // Returns 0, feels down

Front line of performance

For performance-loving folks, stay away from Math.pow() in loops:

let powerPlay = Math.pow(10, decimalPlaces); for (let i = 0; i < largeArray.length; i++) { largeArray[i] = Math.round(largeArray[i] * powerPlay) / powerPlay; // Cause we love numbers and hate lags! }

Dodging floating-point errors

When in danger, rely on external help like decimal.js for a bulletproof shield from floating-point errors:

let Decimal = require('decimal.js'); let superRounded = new Decimal(yourNumber).toFixed(decimalPlaces); // My name is Bond, Rounded Bond.