Search code examples
javascriptparseint

parseInt() only works seem to up to 9999


I have 2 fields/HTML values, in a format similar to this: 7,544 (which represents a monetary amount).

I am removing possible commas using this line:

itemBudget = itemBudget.replace(/,/g, '');

I am comparing these 2 amounts, and alerting the user if the total amount is higher than the budget. I am using this check:

if (parseInt(finalAmount) > parseInt(itemBudget) ) {
   alert('Your total is higher than the budget');
}

This works perfectly -but only when the finalAmount is up to 9999. If it is from 10,000 and up - the test does not pass, even when the final amount is 10000 and the budget is 5000.

What can be going wrong here? Thanks


Solution

  • Make sure you replace finalAmount comma as well.

    Working example:

    var finalAmount = "10,001";
    var itemBudget = "5,000";
    itemBudget = itemBudget.replace(/,/g, '');
    finalAmount = finalAmount.replace(/,/g, '');
    if (parseInt(finalAmount) > parseInt(itemBudget) ) {
       alert('Your total is higher than the budget');
    }