当我单击成本字段为空时,然后单击$0.00 displays。如果用户未输入任何值,我希望这些字段保持空白。有人可以帮我实现该目标吗?下面列出的是我拥有的代码:

var numberWithCommas = function(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

var removeCommas = function(x) {
    return x.replace(/,/g, '');
};

var removeDollarSign = function(x) {
    return x.indexOf('$') === 0 ? x.substr(1) : x;
};

var toNumber = function(num) {
    return isNaN(num) || num === '' || num === null ? 0.00 : num;
};

var toValue = function(str) {
    return toNumber(removeDollarSign(removeCommas(str)));
};

var formatCurrency = function(val) {
    return '$' + numberWithCommas(parseFloat(toValue(val)).toFixed(2));
};

jQ('#costWages, #costExpenses').blur(function(event) {
    event.target.value = formatCurrency(event.target.value);
});

最佳答案

您可以像这样使用Number.prototype.toLocaleString()



const toNumber = num => !num ? 0.00 : num;

const formatCurrency = val => isNaN(val) ? '' :
  (parseFloat(toNumber(val))).toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD'
  });

console.log(formatCurrency())
console.log(formatCurrency(''))
console.log(formatCurrency(null))
console.log(formatCurrency(1234.567))
console.log(formatCurrency('1234.567'))
console.log(formatCurrency('abc'))

09-20 11:47