Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Last active November 25, 2020 03:12
Show Gist options
  • Save VassilisPallas/d73632e9de4794b7dd10b7408f7948e8 to your computer and use it in GitHub Desktop.
Save VassilisPallas/d73632e9de4794b7dd10b7408f7948e8 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