tags:

views:

368

answers:

2

How to format numbers in JavaScript?


A: 

If you google for javascript printf, you'll find lots of implementations.

Paul Dixon
all of which have their own flaws.
holli
+9  A: 

The best you have with JavaScript is toFixed() and toPrecision() functions on your numbers.

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Currency, commas, and other formats will have to be either done by you or a third party library.

SaaS Developer