What follows is a script to format price output in Javascript. The function takes as its input a single number, forces exactly two decimal points, then adds commas for the the thousands, millions, etc. Finally, before returning the output it adds the dollar symbol and a minus sign if applicable.
Depending on where you are using this script, you may not be able to guarantee that only numbers are being passed to the code. For example, you may need to parse a string on the page to get a number before doing math (to apply a discount, calculate a price difference, etc). The first function will strip out non-numeric characters, then convert the number to a price with two or fewer decimal points. If I remember correctly, the multiplication and division by 100 not only serves to round to 2 decimal points, but also avoids a floating number problem (but I can't remember exactly, or I'd test it…).
So for example, say you want to apply a discount of 20% to a product page dynamically (not necessarily a good idea, but it's late and good examples aren't coming to me easily atm). The page lists the product price as "$8.99" in a DIV with the class="price". Using jQuery to get the DIV, you could write:
… or, you can do the entire bit on one line, if readability isn't an issue :-p
Add new comment