Format a number to specific number of decimal places in Javascript.


Here, in this article we will learn on how to format a number to a specific number of decimal places in JavaScript. And for this we will be using toFixed() methods.

For example, if we have a number like:

const number = 123.89645427

And now we want the above number to be formatted to a specific decimal places like 123.8 (one decimal place) or 123.89 (two decimal places). So to do that formatting we will use toFixed() method.

What is toFixed() Method?

The toFixed() method formats a given number and return the number as String. By default, the toFixed() method just remove the fractional part of the number.

Example :

const number = 123.89645427
const formatNumber = number.toFixed()
console.log(formatNumber)

OUTPUT:

"123"
//The number is return as String

Now the returned value is a string representation of the number. Now to convert it back to number we just need to add the + operator before it.

const number = 123.89645427
const formatNumber = +number.toFixed(1)
console.log(formatNumber)

OUTPUT:

123.8

Format a number with two decimals in JavaScript.

Just pass the value 2 in the toFixed() method.

const number = 123.89645427
const formatNumber = +number.toFixed(2)
console.log(formatNumber)

OUTPUT:

123.89

Learn more about toFixed() methods from Mozilla toFixed() Documentation .


💾 Recommended Articles