0

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);
});
2
  • In toNumber , just replace 0.00 with "" ?! Commented Mar 30, 2018 at 14:55
  • @JonasW. OP is still prepending $ sign to numberWithCommas Commented Mar 30, 2018 at 14:59

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

this helps a little, now when I click into the fields and then click out of them, the value that's getting set in the field is just "NaN". What can I do to not have that show up and have the fields just be blank?
After changing "isNaN(val)" to just "!val" in formatCurrency, the issue seems to be resolved now. The fields are now display as blank when I click into them and then click out of them. Thanks @palash
0

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

3 Comments

That should be numberWithCommas(parseFloat(val).toFixed(2) (no need for the toValue)
I tried all the solutions above, and now what's happening is that when I click into the fields and then click out of them, the value that's getting set in the field is this "$NaN". What can I do to not have that show up and have the fields just be blank?
@dan you need to remove call to toValue() from formatCurrency and simply pass val to parseFloat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.