Skip to content

Instantly share code, notes, and snippets.

@angeldelacruzdev
Forked from VassilisPallas/index.ts
Created April 7, 2018 09:14
Show Gist options
  • Save angeldelacruzdev/238b19e8ec5481e43af05c8a6aeac0ff to your computer and use it in GitHub Desktop.
Save angeldelacruzdev/238b19e8ec5481e43af05c8a6aeac0ff to your computer and use it in GitHub Desktop.
Equivalent to PHP function number_format in Javascript
function number_format(number, decimals, dec_point, thousands_point) {
if (number == null || !isFinite(number)) {
throw new TypeError("number is not valid");
}
if (!decimals) {
var len = number.toString().split('.').length;
decimals = len > 1 ? len : 0;
}
if (!dec_point) {
dec_point = '.';
}
if (!thousands_point) {
thousands_point = ',';
}
number = parseFloat(number).toFixed(decimals);
number = number.replace(".", dec_point);
var splitNum = number.split(dec_point);
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
number = splitNum.join(dec_point);
return number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment