如何使用JQuery格式化货币 [英] How can I format currency by using JQuery
本文介绍了如何使用JQuery格式化货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码来格式化货币:
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);
});
但是,这仅适用于"$ 10,000"之类的交易量,如何在一个代码中包含成千上万个?
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?
推荐答案
在香草JS中,这是一个很好的函数,可以处理以下问题:
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) : ""));
};
但是,对于jQuery,您始终可以将其变成插件,或者像下面这样使用它:
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()));
});
});
编辑 我更新了小提琴 JSFiddle
EDIT I updated the fiddle JSFiddle
这篇关于如何使用JQuery格式化货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文