function format_money(n) {
var buf = [],
str = parseFloat(n).toFixed(2).toString(),
i = str.length,
s = str.length - 5,
p = 0
while (++p, i) {
buf.push(str[--i])
if (i && i < s && p % 3 == 0) buf.push(',')
}
return buf.reverse().join('')
}
print(format_money(125.99))
print(format_money(1.99))
print(format_money(15000.99))
print(format_money(1500000.99))
print(format_money(15000000000000.99))
// =>
125.99
1.99
15,000.99
1,500,000.99
15,000,000,000,000.99
Refactorings
No refactoring yet !
Eineki
November 26, 2009, November 26, 2009 05:02, permalink
Just a divertissement.
It should be a good starting point, if not a solution.
If I had more confidence with the regular expressions ....
Maybe there is a chance to avoid the initial padding.
function format_money(n) {
var str, padlen;
str = parseFloat(n).toFixed(2).toString(),
padlen = str.length % 3;
if (0==padlen) padlen=3;
return ("000".substr(padlen)+str).match(/(?:\d{3}\.\d{2}$)|(?:\d{3})/g)
.join(',')
.substr(3-padlen);
}
print(format_money(125.99))
print(format_money(1.99))
print(format_money(15000.99))
print(format_money(1500000.99))
print(format_money(15000000000000.99))
Tj Holowaychuk
November 26, 2009, November 26, 2009 05:42, permalink
It can be done pretty easily with regular expressoins, but im in C text parsing mode lol this is probably faster than regexps too not sure tho yet
Adam
November 26, 2009, November 26, 2009 06:49, permalink
Strangely, I was in need of a similar function yesterday. I was feeling lazy, so it is pretty much a straight up copy of the implementation found in Rails.
numberWithDelimeter(number) {
var delimeter = arguments[1] || ",";
var separator = arguments[2] || ".";
var parts = number.toString().split(".");
parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/, "$1" + delimeter);
return parts.join(separator);
};
Tj Holowaychuk
November 26, 2009, November 26, 2009 06:59, permalink
damn, mine is twice as slow lol to much baggage along with js arrays blah blah o well
Livingston Samuel
January 5, 2010, January 05, 2010 10:13, permalink
here is my refactoring,
var formatCurrency = function (num, seperator, decimal) {
var format_seperator = seperator || ",",
decimal_seperator = decimal || ".",
parts = parseFloat(num, 10).toString().split(decimal_seperator);
parts[0] = parts[0].split("").reverse().join("").match(/(\d{1,3})/g).join(format_seperator).split("").reverse().join("");
if (parts.length === 1) {
parts[1] = "00";
}
return parts.join(decimal_seperator);
};
Just needed to whip up a really quick routine for formatting money