Skip to content

Instantly share code, notes, and snippets.

@krmgns
Last active February 23, 2024 01:30
Show Gist options
  • Save krmgns/e65188703ec063a1fa7a046463311a15 to your computer and use it in GitHub Desktop.
Save krmgns/e65188703ec063a1fa7a046463311a15 to your computer and use it in GitHub Desktop.
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, ',', ' '));
function numberFormat(num, dec = 0, dsep = '.', tsep = ',') {
if (!Number.isFinite(num = Number(num))) {
return;
}
var [base, decs] = num.toFixed(dec).split('.', 2);
var seps = '';
while (base.length > 3) {
seps = tsep + base.slice(base.length - 3) + seps;
base = base.slice(0, base.length - 3);
}
return base + seps + (dec ? ('.' + decs) : '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment