Created
November 17, 2016 10:40
-
-
Save mdjaman/e15ad009107dfaaab6585427649f127f 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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