Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

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:

1
2
3
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