A JavaScript Currency Conversion Script

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.

Join us in our newest publication:

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 '

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.

+ 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:


.reverse() reverses our array:


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


.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)”:


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


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


.join(”) makes them a string again:


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.

Share and Enjoy !

0Shares
0 0