Last active
November 20, 2017 13:43
-
-
Save isuke01/716be444651be2e8899c750b19c229e9 to your computer and use it in GitHub Desktop.
JS format number
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
/** | |
* //https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript#answer-14428340 | |
* Number.prototype.format(n, x, s, c) | |
* | |
* @param integer n: length of decimal | |
* @param integer x: length of whole part | |
* @param mixed s: sections delimiter | |
* @param mixed c: decimal delimiter | |
*/ | |
Number.prototype.format = function(n, x, s, c) { | |
var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', | |
num = this.toFixed(Math.max(0, ~~n)); | |
return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); | |
}; | |
12345678.9.format(2, 3, '.', ','); // "12.345.678,90" | |
123456.789.format(4, 4, ' ', ':'); // "12 3456:7890" | |
12345678.9.format(0, 3, '-'); // "12-345-679" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment