Here you’ll learn how you can format a number to 2 decimal places without rounding it off.
By default, the toFixed() method would round off the number to the specified digits but with rounding in consideration. To avoid this default behavior, you can first multiple the number by 100 and then use Math.floor() to get rid of the decimal digits. You can then divide the number by 100 to get the original number of digits. Here’s an example to demonstrate the same:
const someNumber = 123.456789
const flooredNumber = Math.floor(someNumber * 100)
console.log(flooredNumber)
const formattedNumber = flooredNumber / 100
console.log(formattedNumber)
//output
12345
123.45
Code language: JavaScript (javascript)
You’d notice that 123.456789 has been now converted to 123.45. You can of course do the above computation in one line as follows:
const someNumber = 123.456789
const formattedNumber = Math.floor(someNumber * 100) / 100
console.log(formattedNumber)
//output
123.45
Code language: JavaScript (javascript)
To do the same but with three decimal places instead of two, you can multiply and divide by 1000 instead:
const anotherNumber = 123.456789
const formattedNumber = Math.floor(anotherNumber * 1000) / 1000
console.log(formattedNumber)
//output
123.456
Code language: JavaScript (javascript)
You can further refactor the code to have a function which multiplies by the number of 10s required as follows:
function getMultiplier(digits) {
let multiplier = 1
for (let i = 0; i < digits; i++) {
multiplier = multiplier * 10
}
return multiplier
}
const anotherNumber = 123.456789
const formattedNumber =
Math.floor(anotherNumber * getMultiplier(2)) / getMultiplier(2)
console.log(formattedNumber)
//output
123.45
Code language: JavaScript (javascript)
Another way to format a number without rounding off is by using a regex. Here’s an example to demonstrate the same:
const someNumber = 12.34567
const formattedNumber = Number(
someNumber.toString().match(/^\d+(?:\.\d{0,2})?/)
)
console.log(formattedNumber)
//output
12.34
Code language: JavaScript (javascript)
If you have any doubts or suggestions, let me know in the comments section below!