How can I format currency by using JQuery [duplicate]

故事扮演 提交于 2019-11-30 15:39:28

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!