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: http://jsbin.com/IhUNAJo/2/embed?html,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.

2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete
  2. That gives off an impression of being fabulous anyway i am still not very beyond any doubt that I like it. At any rate will look much more into it and choose by and by!  Forex Trading Simplified.

    ReplyDelete