Created
December 13, 2015 11:19
-
-
Save vansosnin/5766e73eec19863cebd1 to your computer and use it in GitHub Desktop.
PHP's number_format function for JS
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, dec_point, thousands_sep) { | |
var i, j, kw, kd, km; | |
if (isNaN(decimals = Math.abs(decimals))) { | |
decimals = 2; | |
} | |
if (dec_point == undefined) { | |
dec_point = ","; | |
} | |
if (thousands_sep == undefined) { | |
thousands_sep = "."; | |
} | |
i = parseInt(number = (+number || 0).toFixed(decimals)) + ""; | |
if ((j = i.length) > 3) { | |
j = j % 3; | |
} else { | |
j = 0; | |
} | |
km = (j ? i.substr(0, j) + thousands_sep : ""); | |
kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep); | |
kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : ""); | |
return km + kw + kd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment