Using `toFixed()` method in JavaScript

In this post, we are going to learn about formatting a number to specific decimal places in JavaScript using the toFixed() method.

Consider that we have a number like this.

const num  = 123.1390;

Now, we need to format the above number according to specific decimal places like 123.12 or 123.139.

Using toFixed() Method

The toFixed() method formats a number and returns the string representation of a number. Be default the toFixed() method removes the fractional part.

It also accepts the optional argument called digits, which means we need to specify the number of digits after the decimal point.

Let’s see an example:

const num  = 123.1390
            // fractional part is removed
console.log(num.toFixed()); // "123"

Now, you can see that our number is converted to a string representation. Because of this, we need to convert the string back to a number by adding + operator.

console.log(+num.toFixed()); // 123

Formatting Number to Two Decimal places

To format a number to two decimal places we need to pass 2 as an argument to the toFixed() method.

const num  = 123.1390
console.log(+num.toFixed(2)); // 123.13

Similarly, we can format a number according to our needs like this:

const num  = 123.1390
          // 1 decimal place
console.log(+num.toFixed(1)); // 123.1
          // 2 decimal places
console.log(+num.toFixed(2)); // 123.13
          // 3 decimal places
console.log(+num.toFixed(3)); // 123.139

This post, we discuss how to use JavaScript’s toFixed() method in order to format a number to a specific number of decimal places. Hope this post will help you! Thank you!

#javascript #developer #programming #tutorial

Using `toFixed()` method in JavaScript
23.65 GEEK