【问题标题】:How can I format currency by using JQuery [duplicate]如何使用 JQuery 格式化货币 [重复]
【发布时间】:2014-07-20 21:29:23
【问题描述】:

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

$('#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 美元”或类似的数量,我如何在一个代码中包含数千、数百和数百万?

【问题讨论】:

    标签: php jquery currency


    【解决方案1】:

    这是处理事情的 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

    【讨论】:

    • 感谢您的回复@faino,我不是插件的粉丝.. 我只想在文件中包含 jquery 而不使用任何插件.. 如果我将使用此代码您提供的: $('#currency').keyup(function(e){ $(this).val(format($(this).val())); });我必须包含插件吗?
    • 不,你没有,我对原始脚本做了一些修改,如果你看看更新后的小提琴,你会看到它在做什么。
    • 正是我要找的...非常感谢!
    • @Swanney_14 如果这对您有帮助,您可以接受/支持这个答案
    • 那是不久前的事了,我花了一点时间才找到它。这是我使用的代码:if (isNumberKey(e) &amp;&amp; !e.shiftKey) { $(this).val(format($(this).val())); }
    【解决方案2】:

    你可以使用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.

    【讨论】:

    • 感谢您的回复,真的关闭了我要找的东西!当客户输入数字时,我唯一想在输入中包含它,它会在输入本身中改变..
    • @Swanney_14 你是什么意思?事实上,防止用户输入非数字字符的问题是另一个问题,将数字转换为货币格式的问题是另一个问题。它们完全是格式化数据的两个独立步骤。
    • @Swanney_14 我知道您接受了最佳答案,但是我刚刚更新了我的答案,您应该在下次提问之前提及您的确切要求。
    • 是的,谢谢.. 很抱歉我的问题没有具体说明.. 那是我在寻找谢谢!
    【解决方案3】:

    这里是一个使用 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

    【讨论】:

    • 感谢您的回复。现在,这是转换的示例,我正在寻找格式作为客户端键入数字..
    • 您可以使用 onchange 事件,当用户类型将被更改时。这里是一个演示:jsfiddle.net/2wEe6/72。为您的目标使用输入更改事件。
    • 这正是我想要的,非常感谢!
    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2011-09-16
    • 1970-01-01
    相关资源
    最近更新 更多