Tuesday, 11 March 2014

Format numbers as money in JavaScript



You can also extend the prototype of Number object to add additional support of any number of decimals [0 .. n] and the size of number groups [0 .. x]:
Number.prototype.format = function(n, x) {
    var re = '(\\d)(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$1,');
};

1234..format();           // "1,234"
12345..format(2);         // "12,345.00"
123456.7.format(3, 2);    // "12,34,56.700"
123456.789.format(2, 4);  // "12,3456.79"

var num = 10000;
alert(num.format(2));         //10,000.00
alert(Number(1234).format());      //1,234
alert(Number(123456.7).format(3,2));      //12,34,56.700


No comments:

Post a Comment