-
-
Save angeldelacruzdev/238b19e8ec5481e43af05c8a6aeac0ff to your computer and use it in GitHub Desktop.
Equivalent to PHP function number_format in Javascript
This file contains 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_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