{"id":635,"date":"2011-11-28T16:28:57","date_gmt":"2011-11-28T22:28:57","guid":{"rendered":"http:\/\/cssnewbie.com\/?p=635"},"modified":"2022-09-05T05:26:20","modified_gmt":"2022-09-05T05:26:20","slug":"javascript-currency-conversion-script","status":"publish","type":"post","link":"https:\/\/cssdeck.com\/blog\/javascript-currency-conversion-script\/","title":{"rendered":"A JavaScript Currency Conversion Script"},"content":{"rendered":"<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-641\" src=\"https:\/\/cssdeck.com\/blog\/wp-content\/uploads\/2011\/11\/currency-convert-example.png\" alt=\"\" width=\"500\" height=\"100\" \/><\/p>\n<p>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&#8217;s no built-in function for it, and it&#8217;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&#8217;d share it with you-all.<\/p>\n<p>The little <a href=\"https:\/\/www.tutorialstonight.com\/js\/js-function\">JavaScript function<\/a> below does exactly one thing: it converts numbers (integers, floats, strings, whatever) into formatted currency. My example is in US dollars, but it&#8217;d be a quick change to make it work for other currencies as well.<\/p>\n<h3>The Problem This Solves<\/h3>\n<p>I wrote this script because I had to display dollar amounts in a &#8220;friendly&#8221; format in several places on a website, but I wasn&#8217;t being handed friendly numbers by the server. The numbers never included commas, of course. But there&#8217;s also the problem of whole-dollar and multiple-of-ten-cent amounts: I would have &#8220;500&#8221; when the user would expect &#8220;500.00&#8221;, or &#8220;250.2&#8221; when the user would expect &#8220;250.20&#8221;.<!--more--><\/p>\n<h3>The JavaScript<\/h3>\n<p>First the script, then the explanation.<\/p>\n<pre lang=\"javascript\">function toUSD(number) {\n    var number = number.toString(), \n    dollars = number.split('.')[0], \n    cents = (number.split('.')[1] || '') +'00';\n    dollars = dollars.split('').reverse().join('')\n        .replace(\/(\\d{3}(?!$))\/g, '$1,')\n        .split('').reverse().join('');\n    return '<\/pre>\n<h3>The Explanation<\/h3>\n<p>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 &#8220;dollars&#8221; variable is everything before the decimal point. The &#8220;cents&#8221; variable is everything after the decimal point, plus a couple of extra zeroes just to be safe (we&#8217;ll lop off extra zeroes later). If there is no decimal point, cents becomes &#8220;00&#8221;.<\/p>\n<p>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&#8217;ll walk through each of the manipulations one by one to show you what we have after each one. We&#8217;ll assume we have an initial dollar string of &#8220;123456&#8221;.<\/p>\n<p><strong>dollars.split(&#8221;)<\/strong> converts our string into an array of individual digits:<\/p>\n<pre>[\"1\", \"2\" ,\"3\" , \"4\", \"5\", \"6\"]<\/pre>\n<p><strong>.reverse()<\/strong> reverses our array:<\/p>\n<pre>[\"6\", \"5\", \"4\", \"3\", \"2\", \"1\"]<\/pre>\n<p><strong>.join(&#8221;)<\/strong> turns our array back into a single string again:<\/p>\n<pre>\"654321\"<\/pre>\n<p><strong>.replace(\/(\\d{3}(?!$))\/g, &#8216;$1,&#8217;)<\/strong> is a complicated (for me) regular expression that basically says &#8220;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)&#8221;:<\/p>\n<pre>\"654,321\"<\/pre>\n<p><strong>.split(&#8221;)<\/strong> converts our newly comma&#8217;d string to an array again:<\/p>\n<pre>[\"6\", \"5\", \"4\", \",\", \"3\", \"2\", \"1\"]<\/pre>\n<p><strong>.reverse()<\/strong> puts the numbers back in the proper order:<\/p>\n<pre>[\"1\", \"2\", \"3\", \",\", \"4\", \"5\", \"6\"]<\/pre>\n<p><strong>.join(&#8221;)<\/strong> makes them a string again:<\/p>\n<pre>\"123,456\"<\/pre>\n<p>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&#8217;m using slice to only return the first two digits in the cents string).<\/p>\n<h3>How To Internationalize<\/h3>\n<ul>\n<li>If your currency of choice uses periods instead of commas as a thousands-place divider, change &#8216;$1,&#8217; in the replace function to be &#8216;$1.&#8217; Instead.<\/li>\n<li>If you use a comma instead of a period between dollars and cents, change &#8220;dollars + &#8216;.'&#8221; in the return line to read &#8220;dollars + &#8216;,'&#8221; instead. If you are starting with a number that uses a comma to denote a decimal, you&#8217;d also need to change the dollars and cents variables to have &#8220;.split(&#8216;,&#8217;)&#8221; instead of &#8220;.split(&#8216;.&#8217;)&#8221;.<\/li>\n<li>To use something other than a dollar sign in the currency, simply replace the &#8216;$&#8217; in the return line with your currency sign.<\/li>\n<\/ul>\n<h3>See a Demo<\/h3>\n<p>If you&#8217;d like to see it in action, <a href=\" http:\/\/cssnewbie.com\/example\/currency-conversion\/\">here&#8217;s a demo.<\/a><\/p>\n<pre lang=\"javascript\">+ dollars + '.' + cents.slice(0, 2); }<\/pre>\n<h3>The Explanation<\/h3>\n<p>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 &#8220;dollars&#8221; variable is everything before the decimal point. The &#8220;cents&#8221; variable is everything after the decimal point, plus a couple of extra zeroes just to be safe (we&#8217;ll lop off extra zeroes later). If there is no decimal point, cents becomes &#8220;00&#8221;.<\/p>\n<p>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&#8217;ll walk through each of the manipulations one by one to show you what we have after each one. We&#8217;ll assume we have an initial dollar string of &#8220;123456&#8221;.<\/p>\n<p><strong>dollars.split(&#8221;)<\/strong> converts our string into an array of individual digits:<\/p>\n<pre><\/pre>\n<p><strong>.reverse()<\/strong> reverses our array:<\/p>\n<pre><\/pre>\n<p><strong>.join(&#8221;)<\/strong> turns our array back into a single string again:<\/p>\n<pre><\/pre>\n<p><strong>.replace(\/(\\d{3}(?!$))\/g, &#8216;$1,&#8217;)<\/strong> is a complicated (for me) regular expression that basically says &#8220;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)&#8221;:<\/p>\n<pre><\/pre>\n<p><strong>.split(&#8221;)<\/strong> converts our newly comma&#8217;d string to an array again:<\/p>\n<pre><\/pre>\n<p><strong>.reverse()<\/strong> puts the numbers back in the proper order:<\/p>\n<pre><\/pre>\n<p><strong>.join(&#8221;)<\/strong> makes them a string again:<\/p>\n<pre><\/pre>\n<p>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&#8217;m using slice to only return the first two digits in the cents string).<\/p>\n<h3>How To Internationalize<\/h3>\n<ul>\n<li>If your currency of choice uses periods instead of commas as a thousands-place divider, change &#8216;$1,&#8217; in the replace function to be &#8216;$1.&#8217; Instead.<\/li>\n<li>If you use a comma instead of a period between dollars and cents, change &#8220;dollars + &#8216;.'&#8221; in the return line to read &#8220;dollars + &#8216;,'&#8221; instead. If you are starting with a number that uses a comma to denote a decimal, you&#8217;d also need to change the dollars and cents variables to have &#8220;.split(&#8216;,&#8217;)&#8221; instead of &#8220;.split(&#8216;.&#8217;)&#8221;.<\/li>\n<li>To use something other than a dollar sign in the currency, simply replace the &#8216;$&#8217; in the return line with your currency sign.<\/li>\n<\/ul>\n<h3>See a Demo<\/h3>\n<p>If you&#8217;d like to see it in action, <a href=\" http:\/\/cssnewbie.com\/example\/currency-conversion\/\">here&#8217;s a demo.<\/a><\/p>\n<div class=\"wp-socializer wpsr-share-icons \" data-lg-action=\"show\" data-sm-action=\"show\" data-sm-width=\"768\" ><h3>Share and Enjoy !<\/h3><div class=\"wpsr-si-inner\"><div class=\"wpsr-counter wpsrc-sz-32px\" style=\"color:#000\"><span class=\"scount\"><span data-wpsrs=\"\" data-wpsrs-svcs=\"facebook,twitter,linkedin,pinterest,print,pdf\">0<\/span><\/span><small class=\"stext\">Shares<\/small><\/div><div class=\"socializer sr-popup sr-32px sr-circle sr-opacity sr-pad sr-count-1 sr-count-1\"><span class=\"sr-facebook\"><a rel=\"nofollow\" href=\"https:\/\/www.facebook.com\/share.php?u=\" target=\"_blank\"  title=\"Share this on Facebook\"  style=\"color: #ffffff\" ><i class=\"fab fa-facebook-f\"><\/i><span class=\"ctext\"><span data-wpsrs=\"\" data-wpsrs-svcs=\"facebook\">0<\/span><\/span><\/a><\/span>\n<span class=\"sr-twitter\"><a rel=\"nofollow\" href=\"https:\/\/twitter.com\/intent\/tweet?text=%20-%20%20\" target=\"_blank\"  title=\"Tweet this !\"  style=\"color: #ffffff\" ><i class=\"fab fa-twitter\"><\/i><\/a><\/span>\n<span class=\"sr-linkedin\"><a rel=\"nofollow\" href=\"https:\/\/www.linkedin.com\/sharing\/share-offsite\/?url=\" target=\"_blank\"  title=\"Add this to LinkedIn\"  style=\"color: #ffffff\" ><i class=\"fab fa-linkedin-in\"><\/i><\/a><\/span>\n<span class=\"sr-pinterest\"><a rel=\"nofollow\" href=\"https:\/\/www.pinterest.com\/pin\/create\/button\/?url=&amp;media=&amp;description=\" target=\"_blank\"  title=\"Submit this to Pinterest\"  style=\"color: #ffffff\" data-pin-custom=\"true\"><i class=\"fab fa-pinterest\"><\/i><span class=\"ctext\"><span data-wpsrs=\"\" data-wpsrs-svcs=\"pinterest\">0<\/span><\/span><\/a><\/span>\n<span class=\"sr-print\"><a rel=\"nofollow\" href=\"https:\/\/www.printfriendly.com\/print?url=\" target=\"_blank\"  title=\"Print this article \"  style=\"color: #ffffff\" ><i class=\"fa fa-print\"><\/i><\/a><\/span>\n<span class=\"sr-pdf\"><a rel=\"nofollow\" href=\"https:\/\/www.printfriendly.com\/print?url=\" target=\"_blank\"  title=\"Convert to PDF\"  style=\"color: #ffffff\" ><i class=\"fa fa-file-pdf\"><\/i><\/a><\/span><\/div><\/div><\/div>","protected":false},"excerpt":{"rendered":"<p>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&#8217;s no built-in function for it, and it&#8217;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&#8217;d share it with you-all. [&#8230;]<\/p>\n<p><a class=\"more-link article\" href=\"https:\/\/cssdeck.com\/blog\/javascript-currency-conversion-script\/\" title=\"Click to read 'A JavaScript Currency Conversion Script'\">Read Article<\/a><\/p>\n","protected":false},"author":18,"featured_media":641,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[184,192],"tags":[224,227,228,237,55,304,375],"_links":{"self":[{"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/posts\/635"}],"collection":[{"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/users\/18"}],"replies":[{"embeddable":true,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/comments?post=635"}],"version-history":[{"count":1,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/posts\/635\/revisions"}],"predecessor-version":[{"id":3646,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/posts\/635\/revisions\/3646"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/media\/641"}],"wp:attachment":[{"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/media?parent=635"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/categories?post=635"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cssdeck.com\/blog\/wp-json\/wp\/v2\/tags?post=635"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}