Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP's number_format() implementation with JavaScript.
/**
* To number format.
* @param {Integer} decimals?
* @param {String} decimalsSeparator?
* @param {String} thousandsSeparator?
* @return {String}
* @links http://php.net/number_format, https://stackoverflow.com/q/2901102
*/
Number.prototype.toNumberFormat = function(decimals, decimalsSeparator, thousandsSeparator) {
decimalsSeparator = decimalsSeparator || '.';
thousandsSeparator = thousandsSeparator || ',';
var numbers = this.toFixed(decimals).split('.');
numbers[0] = numbers[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
return numbers.join(decimalsSeparator);
};
// minified
Number.prototype.toNumberFormat=function(t,r,e){r=r||".",e=e||",";var o=this.toFixed(t).split(".");return o[0]=o[0].replace(/\B(?=(\d{3})+(?!\d))/g,e),o.join(r)};
// examples
var x = Math.random() * 0xffffff;
console.log(x, x.toNumberFormat());
console.log(x, x.toNumberFormat(2));
console.log(x, x.toNumberFormat(2, ',', '.'));
console.log(x, x.toNumberFormat(2, ',', ' '));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.