如何使用JQuery格式化货币

时间:2014-05-31 03:37:45

标签: php jquery currency

我正在尝试使用以下代码格式化货币:

$('#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);
 });  

但这只适用于“$ 10,000”之类的音量或类似的东西,如何在一个代码中包含数千,数百和数百万?

3 个答案:

答案 0 :(得分:13)

这是vanilla JS中一个很好的函数来处理事情:

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) : ""));
};

但是,对于jQuery,您可以随时将其转换为插件,或者只是使用它:

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

修改 我更新了小提琴 JSFiddle

答案 1 :(得分:1)

您可以使用regex来解决此问题,请注意您的输入字段应该阻止用户键入字母/非数字字符,而不是用空字符串替换所有键入的非数字字符,这样做是不专业:

$('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.

答案 2 :(得分:0)

以下是使用jquery插件的示例:

<!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>

请参阅:

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

演示小提琴:jsfiddle.net/2wEe6/72