Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用JQuery格式化货币_Php_Jquery_Currency - Fatal编程技术网

Php 如何使用JQuery格式化货币

Php 如何使用JQuery格式化货币,php,jquery,currency,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

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

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

但这只适用于“10000美元”之类的数量,我怎么能在一个代码中包含数千、数百和数百万

下面是一个使用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>

JQuery格式化货币示例
正文,div{margin:0px auto;padding:0px;}
.main{margin:40px;}
.示例{浮点:左;边距:10px;填充:4px;边框:1px实心#888;宽度:350px;}
.样本h3{边距:-4px;边距底部:10px;填充:4px;背景:#555;颜色:#eee;}
.currencyLabel{display:block;}
//样本1
$(文档).ready(函数()
{
$(“#currencyButton”)。单击(函数()
{
$(“#currencyField”).formatCurrency();
$(“#currencyField”).formatCurrency(“.currencyLabel”);
});
});
//样本2
$(文档).ready(函数()
{
$('.currency').blur(函数()
{
$('.currency').formatCurrency();
});
});
格式货币样本
使用按钮单击设置格式
将货币格式化为Html跨度标记。
$1,220.00
使用模糊设置格式(失去焦点)
请参阅:


Demo fiddle:jsfiddle.net/2wEe6/72

这是一个很好的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) : ""));
};
编辑 我更新了小提琴

您可以使用
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('');
}

谢谢你的回复。现在,这是一个转换的例子,在这里,我寻找的格式是客户端在中键入数字。当用户类型发生更改时,可以使用onchange事件。下面是一个演示:。使用输入更改事件来实现您的目标。这正是我想要的,非常感谢!感谢您的回复@faino,我不喜欢插件。。我只想在文件中包含jquery,而不使用任何插件。。如果我使用您提供的代码:$('#currency').keyup(函数(e){$(this.val)(格式($(this.val());});我必须包括插件吗?不,你不需要,我对原始脚本做了一些修改,如果你看一下更新后的小提琴,你会看到它在做什么。正是我想要的。。。非常感谢@Swanney_14如果这确实有助于你接受/更新这个答案,那是很久以前的事了,我花了一点时间才找到它。这是我使用的代码:
if(isNumberKey(e)和&&!e.shiftKey){$(this.val(format($(this.val());}
谢谢你的回复,真的关闭了我要找的东西!当客户端键入数字时,我唯一想将其包含在输入中的是,输入本身会发生变化。@Swanney_14你是什么意思?事实上,阻止用户键入非数字字符的问题是另一个问题,将数字转换为货币格式的问题是另一个问题。它们是形成数据的两个独立步骤。@Swanney_14我知道你接受了最好的答案,但我刚刚更新了我的答案,你应该在下次提问之前说明你的确切要求。是的,谢谢。。对不起,我的问题不具体。。那是我一直在找的谢谢!
$('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('');
}