Wednesday, October 2, 2013

JavaScript Currency Formatter

I hate details.. that’s where the devil is.  I know it.. that’s what the saying says.  Nevertheless, the details are where many of my problems lie, yet I must continue to deal with them..  Today, my problem involved a number formatter, specifically a currency format.  A web app I’ve been working on is coming along rather smoothly, and using jQuery, jQueryUI and Twitter Bootstrap has given me some pretty cool UI features that I’ve been pleased with.  So, when it came to performing some custom validation and what-not, I started doing pretty cool things, like auto-formatting phone numbers and other numeric values while they were being typed. I then hit a wall, as I needed to apply numeric formatting to a currency value. This is apparently a sore spot for many others, so I thought I would share my Frankenstein creation of a currency formatter.

What did I build, well.. this:,output

Glorious, right!?! Ehh, maybe not, but it's servicable, and I wanted to share it with the world. Here's the code:

How does this work? It's pretty simple. First, I'm using commafy, which is a prototype built by Steven Levithan. I'm using jQuery to capture the keyup\change events to alter my value (although this isn't necessary). Otherwise, I'm simply grabbing the current textbox value, stripping out anything that's not a number or a decimal value, adding comma's to the prefix (value before the decimal), and limiting the number to 2 values after the decimal.

No comments:

Post a Comment