A JavaScript Currency Conversion Script

Published November 28, 2011 by Rob Glazebrook.

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″.

The JavaScript

First the script, then the explanation.

function toUSD(number) {
    var number = number.toString(), 
    dollars = number.split('.')[0], 
    cents = (number.split('.')[1] || '') +'00';
    dollars = dollars.split('').reverse().join('')
        .replace(/(\d{3}(?!$))/g, '$1,')
        .split('').reverse().join('');
    return '$' + dollars + '.' + cents.slice(0, 2);
}

The Explanation

The function expects to be passed one variable: the number you wanted converted. I first convert it to a string for easier manipulation. From that, I create a few more variables. The “dollars” variable is everything before the decimal point. The “cents” variable is everything after the decimal point, plus a couple of extra zeroes just to be safe (we’ll lop off extra zeroes later). If there is no decimal point, cents becomes “00″.

Next, I do a whole heck of a lot of manipulation to the dollars string. This is all to add the commas in the correct places. I’ll walk through each of the manipulations one by one to show you what we have after each one. We’ll assume we have an initial dollar string of “123456″.

dollars.split(”) converts our string into an array of individual digits:

["1", "2" ,"3" , "4", "5", "6"]

.reverse() reverses our array:

["6", "5", "4", "3", "2", "1"]

.join(”) turns our array back into a single string again:

"654321"

.replace(/(\d{3}(?!$))/g, ‘$1,’) is a complicated (for me) regular expression that basically says “add a comma to the end of every group of three numbers, unless it is the last group of three numbers (to avoid trailing commas)”:

"654,321"

.split(”) converts our newly comma’d string to an array again:

["6", "5", "4", ",", "3", "2", "1"]

.reverse() puts the numbers back in the proper order:

["1", "2", "3", ",", "4", "5", "6"]

.join(”) makes them a string again:

"123,456"

After that, all we do is return our manipulated number with a dollar sign out front and a decimal point between dollars and cents (and I’m using slice to only return the first two digits in the cents string).

How To Internationalize

  • If your currency of choice uses periods instead of commas as a thousands-place divider, change ‘$1,’ in the replace function to be ‘$1.’ Instead.
  • If you use a comma instead of a period between dollars and cents, change “dollars + ‘.’” in the return line to read “dollars + ‘,’” instead. If you are starting with a number that uses a comma to denote a decimal, you’d also need to change the dollars and cents variables to have “.split(‘,’)” instead of “.split(‘.’)”.
  • To use something other than a dollar sign in the currency, simply replace the ‘$’ in the return line with your currency sign.

See a Demo

If you’d like to see it in action, here’s a demo.

15 Responses

  1. Shane rutter (reply)

    Thank you for this, think I will find this very useful in futur projects. I’ve came across this issue many times.

  2. Lars Gunther (reply)

    I suggested a number format CSS declaration to the CSS WG a couple of years ago. So far zero interest. http://wiki.csswg.org/ideas/content-formatting

    The problem with separating numbers using commas is that you can no longer read the value using JavaScript, which is bad for some applications.

    In Sweden we use a space, which also mean that numbers may get split across several lines, unless one remembers to use non-breaking space….

  3. Pingback: To Read – A JavaScript Currency Conversion Script | Ralookuh

  4. Geoff (reply)

    @Mario and OP
    To fix the negative number problem you simply add another negative lookahead to the regex. So the new replace is .replace(/(\d{3}(?!$)(?!-))/g, ‘$1,’). Note the (?!-).

    Thanks for sharing this OP, helped me out.

  5. Pingback: Bouncing Balls in the HTML5 Canvas | WarWebDev

  6. Pingback: Bouncing Balls in the HTML5 Canvas | Lunarium Design

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>