Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

U.S. Currency Conversion Using Javascript

A Small JavaScript U.S. Dollar Formatter

If you're like me and work on a lot of e-commerce sites, I'm sure you have come across the need to have a simple function to convert a number to a U.S. Dollar formatted string. If you have scoured Google looking for something, I'm sure you've come across the plethora of "currency" formatting libraries/functions out there. The problem is (at least with me) is that all these functions seem to be large, complicated, monstorous libraries that give you the ability to convert a number into a gazillion different localized currencies. That's fine and dandy if your customer plans on going global, but what if they just want to sell things in the U.S.? That pretty much sums up the majority of my customers.

I've come up with a very simple JavaScript prototype that will convert a number into a nice U.S. Dollar formated string. This function will add the thousands seprator (comma), add the dollar sign ($), add two decimal places and handle negative numbers.

if (!Number.prototype.dollarFormat) {
   // Simple U.S Dollar Formatter - By Doug Jones (MIT Licensed)
   Number.prototype.dollarFormat = function() {
      if (!isNaN(this)) {
         var n = this < 0 ? true : false,
             a = (n ? this * -1 : this).toFixed(2).toString().split("."),
             b = a[0].split("").reverse().join("").replace(/.{3,3}/g, "$&,").replace(/\,$/, "").split("").reverse().join("");
         return((n ? "(" : "") + "$" + b + "." + a[1] + (n ? ")" : ""));
      }
   };
}

It's not the prettiest function at the dance, but it's light weight and does the job. All you have to do is add the prototype to your site and then you can use it like so:

var myValue = 1234567.1;
document.write(myValue.dollarFormat());

> $1,234,567.10

// handles negative numbers too!
var myValue = -123456;
document.write(myValue.dollarFormat());

> ($123,456.00)

You could easily change this to make other currency conversion functions, like euroFormat(), etc, but I'll leave that up to you. Enjoy and let me know if you have any problems.