format thousands 5731193
Compare, speed-wise, these different library-less solutions from SO 5731193
HTML
<!--
Compare, speed-wise, these different library-less solutions from SO 5731193
I seem not to be able to edit any jsPers at the moment, no idea why. Keep getting accused of being spam. So unable to create a proper test env.
This will have to do for now.
//-->
CSS
.lpad { width: 10px; border-left: 1px dotted black; }
.rpad { width: 10px; border-right: 1px dotted black; }
JavaScript
var repeat = 50000;
/**
* This is the old version, with the bugs pointed out
* in terms of negative numbers, and rounding errors
*/
function formatThousandsOld(n, dp){
var s = ''+(Math.floor(n)), d = Math.abs(n % 1), i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r +
(d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};
formatThousandsOld.name = 'formatThousandsOld';
formatThousandsOld.repeat = repeat;
/**
* Fixed new version, which due to using toFixed()
* includes automatic rounding. However, in terms
* of formatting a number, you may not wish to have
* rounding that can change the number you are formatting.
*/
function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
formatThousandsWithRounding.name = 'formatThousandsWithRounding';
formatThousandsWithRounding.repeat = repeat;
/**
* A version of the code that uses split to avoid
* mathematical rounding. Split is slow however.
*/
function formatThousandsSplit(n, dp){
var w = ''+n, a = w.split('.'), s = a[0],
d = (''+(a[1]||0)).substr(0, dp),
i = s.length, r = '';
while ( d.length < dp ) { d += '0'; }
while ( (i-=3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
formatThousandsSplit.name = 'formatThousandsSplit';
formatThousandsSplit.repeat = repeat;
/**
* Another non-rounding function, but this uses
* indexOf which should be faster.
*/
function formatThousandsIndexOf(n, dp){
var s = ''+n, i = s.lastIndexOf('.'), z = i != -1,
a = z ? s.substring(0, i) : s,
b = z ? s.substr(i+1, dp) : ('000000').substr(0, dp),
c = n < 0 ? 1 : 0,
j = a.length, r = '';
while ( b.length < dp ) { b +=...