将 JS 结果格式化为货币格式
Format JS result into Currency Format
我想将结果的格式转换成货币。
JS
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
total += parseFloat($('td.credit:eq(' + column + ')', this).html()) || 0;
})
$(this).html(total);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
结果显示在 class 标签中。我希望它以货币格式显示。例如。 $ x,xxx.xx ($1,234.56)
像这样应该可以解决问题:
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
formattedTotal, numCredit, strCredit
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
strCredit = $('td.credit:eq(' + column + ')', this).html() || "";
console.log(strCredit);
numCredit = Number(strCredit.replace(/[^0-9\.]+/g,""));
console.log(numCredit);
total += parseFloat(numCredit) || 0;
})
formattedTotal = total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
$(this).html('$'+formattedTotal);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
您可以使用 Numeral.js 库。
这是一个示例,如何将 total
变量格式化为货币格式:
$(this).html(numeral(total).format('[=10=],0.00'));
它只有3k,但支持多种不同的格式并且有本地化。
我想将结果的格式转换成货币。 JS
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
total += parseFloat($('td.credit:eq(' + column + ')', this).html()) || 0;
})
$(this).html(total);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
结果显示在 class 标签中。我希望它以货币格式显示。例如。 $ x,xxx.xx ($1,234.56)
像这样应该可以解决问题:
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
formattedTotal, numCredit, strCredit
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
strCredit = $('td.credit:eq(' + column + ')', this).html() || "";
console.log(strCredit);
numCredit = Number(strCredit.replace(/[^0-9\.]+/g,""));
console.log(numCredit);
total += parseFloat(numCredit) || 0;
})
formattedTotal = total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
$(this).html('$'+formattedTotal);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
您可以使用 Numeral.js 库。
这是一个示例,如何将 total
变量格式化为货币格式:
$(this).html(numeral(total).format('[=10=],0.00'));
它只有3k,但支持多种不同的格式并且有本地化。