Skip to content

Instantly share code, notes, and snippets.

@heapwolf
Created October 7, 2010 03:11
Show Gist options
  • Save heapwolf/614496 to your computer and use it in GitHub Desktop.
Save heapwolf/614496 to your computer and use it in GitHub Desktop.
function format(v) {
if(isNaN(v)) {
return v;
}
var val = String(v).split(""),
len = val.length,
neg = String(v).indexOf("-"),
dec = String(v).indexOf("."),
offset = (dec != -1 ? (len - dec) : 0),
start = (len - offset)-3,
end = (neg < 0 ? 0 : 1);
if(neg != -1) {
--len;
}
for(var i = start; i > end; i-=3) {
val.splice(i, 0, ",");
}
return val.join("");
}
function rformat(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
console.log(format(-1113122313.0231)); // 0.036ms
console.log(rformat(-1113122313.0231)); // 0.066ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment