user7151558
user7151558

Reputation:

Is there an easy way to replace NaNs with an empty string in JavaScript?

When I click on the cost fields when they are blank and then click out of the $0.00 displays. I want the fields to remain blank if the user does not enter any value. Can someone help me out how do I achieve that? Listed below is the code that I have:

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);
});

Upvotes: 0

Views: 1917

Answers (2)

palaѕн
palaѕн

Reputation: 73926

You can just use Number.prototype.toLocaleString() for this like:

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'))

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

Your formatCurrency can be simplified as

var formatCurrency = function(val) {
    val = val.replace(/[,$]/g, ''); //remove comma and dollar sign
    return isNaN(val) ? "" : '$' + numberWithCommas(parseFloat(toValue(val)).toFixed(2));
};

Upvotes: 0

Related Questions