Last active
August 29, 2015 14:04
-
-
Save royling/7b1f9070032a413d0027 to your computer and use it in GitHub Desktop.
format number to add thousand separator (e.g. `,`) in js -- inspired by http://www.mredkj.com/javascript/nfbasic.html
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 format(num, fmt) { | |
if (isNaN(Number(num))) { | |
throw new TypeError('Not a number'); | |
} | |
if (typeof fmt.scale == 'number') { | |
num = Number(num).toFixed(fmt.scale); | |
} | |
num = String(num).replace('.', fmt.outDecSep||'.'); | |
var regexp = /(\d+)(\d{3})/; | |
while(regexp.test(num)) { | |
num = num.replace(regexp, ['$1', '$2'].join(fmt.thousandSep||',')); | |
} | |
return num; | |
} |
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 format(input, scale) { | |
if (isNaN(Number(input))) { | |
throw new TypeError('not a number'); | |
} | |
var num = String(Number(input).toFixed(scale)), | |
regexp = /(\d+)(\d{3})/; | |
while (regexp.test(num)) { | |
num = num.replace(regexp, ['$1', '$2'].join(',')); | |
} | |
return num; | |
} |
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 format(input, scale) { | |
var chars = String(Number(input).toFixed(scale)).split('').reverse(), | |
dot = chars.indexOf('.'), | |
integral = chars.slice(dot + 1), | |
decimal = dot > -1 ? chars.slice(0, dot) : [], | |
after = []; | |
integral.forEach(function (c, i) { | |
if (i > 0 && i%3 == 0) { | |
after.push(',') | |
} | |
after.push(c) | |
}); | |
decimal.length && Array.prototype.unshift.apply(after, decimal.concat('.')); | |
return after.reverse().join(''); | |
} |
Author
royling
commented
Aug 6, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment