I often find myself in need to display different numbers and stats in my apps. Many times these numbers are either calculated in Javascript or are retrieved via AJAX as JSON data.
The problem is that Javascript doesn’t supply much in the way of number formatting. This is why I wrote this small utility function to display big numbers with thousand separators. This function handles well any number, either integer or float, positive and negative values.
It receives one parameter that controls the numbers of digits to show after the decimal point, which uses the build-in toFixed method. Note that this also means that the number will be rounded to that decimal point.
I’m posting 2 variations of the function, so you can use whichever of the 2 that you’re more comfortable with.
The prototype version:
Number.prototype.toCommaSeparated = function(decimal){
var parts = Math.abs(this).toFixed(decimal || 0).split('.');
return (this < 0 ? '-' : '') + parts[0].split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(/,$/, '').split('').reverse().join('') + (parts[1] ? '.'+parts[1] : '');
};usage example:
var bigNumber = 1234567; bigNumber.toCommaSeparated();
The functional version:
function toCommaSeparated(num, decimal){
var parts = Math.abs(num).toFixed(decimal || 0).split('.');
return (num < 0 ? '-' : '') + parts[0].split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(/,$/, '').split('').reverse().join('') + (parts[1] ? '.'+parts[1] : '');
};usage example:
var bigNumber = 1234567; toCommaSeparated(bigNumber);
Enjoy!
Subscribe