Twitter RSS

Javascript Number.toCurrency()

by Brett Wejrowski on July 31st, 2009

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:
Posted in Miscellaneous, Programming, simpleCart(js) 2 Comments »


2 Responses to Javascript Number.toCurrency()

Leave a Comment
  1. um, why does 119427.23529 get converted to $119,427.34?

  2. Sorry about that Tom… typo.

Join the Discussion