How to format a decimal number in JavaScript

In JavaScript you can use a built-in method to format a decimal number so that it is displayed using, at most, x decimal places. Here is an example:

   
var num = 3.1356;
var x = 3;
alert(num.toFixed(x)); // displays 3.136

As you may have guessed the method is toFixed. It accepts one parameter which is the number of decimal places to take into account.

Note: The number gets rounded as you can notice by the example above.

comments powered by Disqus