1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
function thousdands(num, decpoint, sep){ if (arguments.length == 2) { sep = ","; } if (arguments.length == 1) { sep = ","; decpoint = "."; } num = num.toString(); a = num.split(decpoint); x = a[0]; y = a[1]; z = ""; if (typeof(x) != "undefined") { for (i=x.length-1; i>=0; i--){z += x.charAt(i);} z = z.replace(/(\d{3})/g, "$1" + sep); if (z.slice(-sep.length) == sep){z = z.slice(0, -sep.length);} x = ""; for (i=z.length-1; i>=0; i--){x += z.charAt(i);} if (typeof(y) != "undefined" && y.length > 0){x += decpoint + y;} } return x; }
Refactorings
No refactoring yet !
Jeremy Weiskotten
November 29, 2007, November 29, 2007 18:04, permalink
Retained the core algorithm but extracted the function to reverse the string, renamed some variables for clarity, and fixed the misspelling of the function name. <shill type="shameless">Don't forget to rate this if you like it!</shill>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
String.prototype.reverse = function() { var s = ""; for (i = this.length; i > 0; i--) { s += this.substring(i-1,i); } return s; } function thousands(num, decpoint, sep) { if (arguments.length < 3) { sep = ","; } if (arguments.length < 2) { decpoint = "."; } x = ""; parts = num.toString().split(decpoint); int_part = parts[0]; dec_part = parts[1]; if (typeof(int_part) != "undefined") { x = int_part.reverse().replace(/(\d{3})/g, "$1" + sep).reverse(); // remove extra separator? if (x.slice(0, sep.length) == sep) { x = x.slice(sep.length, x.length); } // recombine the parts if (typeof(dec_part) != "undefined" && dec_part.length > 0) { x += decpoint + dec_part; } } return x; }
Emmett
November 29, 2007, November 29, 2007 19:12, permalink
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//This reverse is much, much faster String.prototype.reverse = function(){ return this.split("").reverse().join(""); } //This function gets even shorter if you don't bother with configurable seperators function thousands(num, decpoint, sep){ if (arguments.length < 3) { sep = ","; } if (arguments.length < 2) { decpoint = "."; } // this requires strong regex-fu: // match( an optional list of numbers up to a period, // followed by some number of groups of 1-3 numbers, // followed by an option minus sign var regex = new RegExp("(?:\\d*\\" + decpoint + ")?\\d{1,3}-?", "g"); return num.toString().reverse(). match(regex). join(sep).reverse(); }
Tien Dung
July 25, 2008, July 25, 2008 09:03, permalink
No RegExp refactor :)
1 2 3 4 5 6 7 8 9 10 11 12
function thousands(num, decpoint, sep) { decpoint = decpoint || "."; sep = sep || ","; var i = num.indexOf(decpoint); if (i < 0) { i = num.length; } do { i -= 3; num = num.substr(0, i) + sep + num.substr(i); } while (i > 3); return num; }
Formats numbers with thousand seperators.