Built-in methods are very helpful as they make our code cleaner and save us time. We don’t have to write the whole functionality ourselves, instead, it’s given to us, and we just call that method when we require that specific functionality. One such built-in method is the toFixed() method.
The toFixed() method was introduced in ES3 and is a built-in number method that rounds off a number to some specific number of decimals and returns that number as a string. As it is a number class built-in method hence it can only be called with a number datatype. The syntax for the toFixed() method is:
The toFixed() method takes the number as an argument which is used to specify the number of decimals one needs rounding off. It is an optional argument and if you don’t pass it to the toFixed() method then by default toFixed() method will take 0 in place of the number and a string will be returned with no digits after the decimal point.
Now that we know what is the toFixed() method, let us format numbers using examples:
Let us go through a simple example where first we will initialize a variable with a number and then call the toFixed() method on that number by displaying the returned string in the console log:
console.log(myNum.toFixed(2)); // 19.57
We will see that the myNum will round off to 19.57 as we have passed 2 as an argument to the toFixed() method:
In this example, we will test the default behaviour of toFixed() method by not passing any argument to the toFixed() method:
console.log(myNum.toFixed()); // 19
We will see that the number is returned as a string and is round off but without any decimals:
Now let’s see another case where suppose you pass 10 as an argument to the toFixed() method but the number you are calling the method on does not have this many decimal places and has fewer decimal places than 10.
console.log(myNum.toFixed(10)); // 19.5678000000
In this case, we will see that the toFixed() method adds extra 0s to the output hence returning a string that has 10 decimal places:
The toFixed() method was introduced in ECMAScript 3 and is used with a number class that returns a string rounded off with the specified number of digits present after the decimal point. The toFixed() method is supported by all the major browsers available for example, Google Chrome, Mozilla Firefox, Microsoft Edge, etc.