
It turns out that converting random numbers into formatted currency (with dollar signs, commas, and periods) is more difficult in JavaScript than I would have expected. There’s no built-in function for it, and it’s something I run into a lot. The function I wrote has worked well for me on a couple of projects now, so I thought I’d share it with you-all.
The little JavaScript function below does exactly one thing: it converts numbers (integers, floats, strings, whatever) into formatted currency. My example is in US dollars, but it’d be a quick change to make it work for other currencies as well.
The Problem This Solves
I wrote this script because I had to display dollar amounts in a “friendly” format in several places on a website, but I wasn’t being handed friendly numbers by the server. The numbers never included commas, of course. But there’s also the problem of whole-dollar and multiple-of-ten-cent amounts: I would have “500″ when the user would expect “500.00″, or “250.2″ when the user would expect “250.20″. Read the rest…







