Skip to content

Instantly share code, notes, and snippets.

@angeldelacruzdev
Created August 10, 2017 21:33
Show Gist options
  • Save angeldelacruzdev/361c7fc0df589d0c726e6585f073df22 to your computer and use it in GitHub Desktop.
Save angeldelacruzdev/361c7fc0df589d0c726e6585f073df22 to your computer and use it in GitHub Desktop.
number_format(number, decimals, decPoint, thousandsSep) in JavaScript, known from PHP. It formats a number to a string with grouped thousands, with custom seperator and custom decimal point
function number_format(number, decimals, decPoint, thousandsSep){
decimals = decimals || 0;
number = parseFloat(number);
if(!decPoint || !thousandsSep){
decPoint = '.';
thousandsSep = ',';
}
var roundedNumber = Math.round( Math.abs( number ) * ('1e' + decimals) ) + '';
var numbersString = decimals ? roundedNumber.slice(0, decimals * -1) : roundedNumber;
var decimalsString = decimals ? roundedNumber.slice(decimals * -1) : '';
var formattedNumber = "";
while(numbersString.length > 3){
formattedNumber += thousandsSep + numbersString.slice(-3)
numbersString = numbersString.slice(0,-3);
}
return (number < 0 ? '-' : '') + numbersString + formattedNumber + (decimalsString ? (decPoint + decimalsString) : '');
}
//english format
number_format( 1234.50, 2, '.', ',' ); // ~> "1,234.50"
//german format
number_format( 1234.50, 2, ',', '.' ); // ~> "1.234,50"
//french format
number_format( 1234.50, 2, '.', ' ' ); // ~> "1 234.50"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment