Skip to content

Instantly share code, notes, and snippets.

@royling
Last active August 29, 2015 14:04
Show Gist options
  • Save royling/7b1f9070032a413d0027 to your computer and use it in GitHub Desktop.
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
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;
}
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;
}
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('');
}
@royling
Copy link
Author

royling commented Aug 6, 2014

format('1234.567', {scale: 2, outDecSep: ',', thousandSep: '.'}) // => 1.234,57

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment