php 如何使用 JQuery 格式化货币

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23966148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:03:55  来源:igfitidea点击:

How can I format currency by using JQuery

phpjquerycurrency

提问by Swanney_14

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?

但这仅适用于诸如“10,000 美元”之类的数量,我如何在一个代码中包含数千、数百和数百万?

回答by faino

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

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

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

然而,对于 jQuery,你总是可以把它变成一个插件,或者像这样使用它:

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

EDITI updated the fiddle JSFiddle

编辑我更新了小提琴 JSFiddle

回答by King King

You can use regexin 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:

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

演示。

回答by Systematix Infotech

Here is an example using jquery plugin:

下面是一个使用 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=",220.00" />
                <input type="button" id="currencyButton" value="Convert" />

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

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

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

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

Please refer :

请参考:

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

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

Demo fiddle: jsfiddle.net/2wEe6/72

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