Javascript Number.toCurrency()
While working on simpleCart(js) 2.0 and a few shopping carts for clients, I found myself writing several helper functions for formatting strings and numbers. One of the most useful helpers was a toCurrency() method for numbers:
var myNumber = 8.3; alert( myNumber.toCurrency() ); //alerts "$8.30" myNumber = 119427.23529; alert( myNumber.toCurrency() ); //alerts "$119,427.24" myNumber = 1231; alert( myNumber.toCurrency( "€" ) ); //alerts "€1,231.00"
The dollar sign is default, but you can replace it with any symbol in the function call.
Just copy this code to your js file and enjoy! (This code also implements a reverse() method for strings that you might find useful.)
String.prototype.reverse=function(){
return this.split("").reverse().join("");
}
Number.prototype.withCommas=function(){
var x=6,y=parseFloat(this).toFixed(2).toString().reverse();
while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}
return y.reverse();
}
Number.prototype.toCurrency=function(){
return(arguments[0]?arguments[0]:"$")+this.withCommas();
}
Tags: currency, javascript, price formatting, simpleCart(js)
Posted in Miscellaneous, Programming, simpleCart(js) 2 Comments »



Delicious
StumbleUpon
Facebook
Reddit
um, why does 119427.23529 get converted to $119,427.34?
Sorry about that Tom… typo.