5

I am trying to format currency by using this code below:

$('#currency').keyup(function(e){
   var val = $(this).val();
   val = val.replace(/[^0-9]/g,'');
   if(val.length >= 2)
   val = '$' + val.substring(0,2) + ',' + val.substring(2);
   if(val.length >= 6)
   val = val.substring(0,7) + val.substring(7);
   if(val.length > 7)
   val = val.substring(0,7); 
   $(this).val(val);
 });  

But that would work only for volume such as "$10,000" or something like that, How can I include thousands, hundreds, and millions in one code?

Swanney_14
  • 53
  • 1
  • 1
  • 5

3 Answers3

14

Here is a nice function in vanilla JS that handles things:

var format = function(num){
    var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
    if(str.indexOf(".") > 0) {
        parts = str.split(".");
        str = parts[0];
    }
    str = str.split("").reverse();
    for(var j = 0, len = str.length; j < len; j++) {
        if(str[j] != ",") {
            output.push(str[j]);
            if(i%3 == 0 && j < (len - 1)) {
                output.push(",");
            }
            i++;
        }
    }
    formatted = output.reverse().join("");
    return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};

However, for jQuery, you could always turn it into a plug-in, or just use it like:

$(function(){
    $("#currency").keyup(function(e){
        $(this).val(format($(this).val()));
    });
});

EDIT I updated the fiddle JSFiddle

faino
  • 3,194
  • 15
  • 17
  • Thanks for your response @faino, I am not a fan of a plug-in.. i just want to include jquery in the file not using any plug-in.. If I will use this code that you provided: $('#currency').keyup(function(e){ $(this).val(format($(this).val())); }); Do I have to include plug-in? – Swanney_14 May 31 '14 at 03:54
  • No you don't, I did some modifications to the original script and if you take a look at the updated fiddle, you'll see what it's doing. – faino May 31 '14 at 04:11
  • @Swanney_14 if this did helped you can kindly accept/upvote this answer – user1978142 May 31 '14 at 04:20
  • I would definitely do that! – Swanney_14 May 31 '14 at 04:26
  • there is a small issue (which can be fixed easily) with this code, try using ***Left Arrow*** key, you see it can't move to the digit you want it to move to. – King King May 31 '14 at 04:37
  • after trying numerous Javasript and Jquery plugins online, this is the first I found that actually worked! I had to wrap it in an if statement to only allow numbers and decimals, but that was easy. – dmikester1 Oct 20 '14 at 21:08
  • @dmikester1 - did you want to share how you did this for others? – ovann86 Jun 10 '15 at 01:11
  • 1
    That was a while ago, took me a bit to find it. Here was the code I used: `if (isNumberKey(e) && !e.shiftKey) { $(this).val(format($(this).val())); }` – dmikester1 Jun 10 '15 at 13:35
  • I changed the return line in order to show hint text when all input was removed. It could be better but it gets the job done. `var result = "$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""); if (result == "$") { result = ""; } return result;` – codebaum Jan 27 '16 at 15:49
1

You can use regex in solving this problem, note that your input field should prevent user from typing letter/non-digit character, other than replacing all the typed non-digit characters with empty string, doing that is not professional:

$('input').on('input', function(e){    
  $(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
  if(!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){    
  var cb = e.originalEvent.clipboardData || window.clipboardData;      
  if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
  var n = number.split('').reverse().join("");
  var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");    
  return "$" + n2.split('').reverse().join('');
}

Demo.

King King
  • 61,710
  • 16
  • 105
  • 130
  • Thanks you for your response, really close what I am looking for! The only thing I want to include it in input when client typing the number, it would change in the input itself.. – Swanney_14 May 31 '14 at 04:07
  • @Swanney_14 what do you mean? in fact the problem of preventing user from typing non-digit character is another problem, the problem of converting number to currency format is another one. They are totally 2 separate steps of formating your data. – King King May 31 '14 at 04:20
  • @Swanney_14 I know you accepted the best answer however I just updated my answer, you should mention your exact requirement before asking some question next time. – King King May 31 '14 at 04:31
  • Yes, Thank you.. I am sorry for being not specific in my question.. That is was I was looking for Thanks! – Swanney_14 May 31 '14 at 04:33
0

Here is an example using jquery plugin:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>JQuery FormatCurrency Sample</title>
        <script type="text/javascript" src="scripts/jquery-1.2.6.js"></script>
        <script type="text/javascript" src="scripts/jquery.formatCurrency.js"></script>
        <style type="text/css">
            body, div  { margin:0px auto; padding:0px; }

            .main { margin:40px; }

            .sample { float:left; margin:10px; padding:4px; border:1px solid #888; width:350px; }

            .sample h3 { margin:-4px; margin-bottom:10px; padding:4px; background:#555; color:#eee; }

            .currencyLabel { display:block; }        
        </style>
        <script type="text/javascript">
            // Sample 1
            $(document).ready(function()
            {
                $('#currencyButton').click(function()
                {
                    $('#currencyField').formatCurrency();
                    $('#currencyField').formatCurrency('.currencyLabel');
                });
            });

            // Sample 2
            $(document).ready(function()
            {
                $('.currency').blur(function()
                {
                    $('.currency').formatCurrency();
                });
            });
        </script>
    </head>
<body>
    <div class="main">
        <div class="formPage">
            <h1>Format Currency Sample</h1>

            <div class="sample">
                <h3>Formatting Using Button Click</h3>
                <input type="textbox" id="currencyField" value="$1,220.00" />
                <input type="button" id="currencyButton" value="Convert" />

                <div>
                    Formatting Currency to an Html Span tag.
                    <span class="currencyLabel">$1,220.00</span>
                </div>
            </div>

            <div class="sample">
                <h3>Formatting Using Blur (Lost Focus)</h3>

                <input type="textbox" id="currencyField" class='currency' value="$1,220.00" />
            </div>

        </div>
    </div>
</body>
</html>

Please refer :

https://code.google.com/p/jquery-formatcurrency/

Demo fiddle: jsfiddle.net/2wEe6/72

Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31
  • Thank you for your response. Now, That is example of converting, where I am looking for formatting as a client typing numbers in.. – Swanney_14 May 31 '14 at 03:49
  • You can use the onchange event when user type it will get changed.Here is an demo: http://jsfiddle.net/2wEe6/72/. Use input change event for your goal. – Systematix Infotech May 31 '14 at 03:51