1

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped

var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');

function calcVal() {
    var num1 = $oneTimeCostField.val();
    var num2 = $recurringTotalCostField.val();
    var result = parseFloat(num1) + parseFloat(num2);
    if (!isNaN(result)) {
        $totalRetailAmountField.val(result.toFixed(2));
    }
}
    calcVal();
      $oneTimeCostField.on("keydown keyup", function() {
        calcVal();
     });
      $recurringTotalCostField.on("keydown keyup", function() {
        calcVal();
     });
Jared Forth
  • 1,577
  • 6
  • 17
  • 32
erics15
  • 567
  • 1
  • 7
  • 16

2 Answers2

2

That is because parseFloat() converts the string "1,555.00" to the number 1. To convert it to a proper floating point number, it needs to include a single dot only.

console.log(parseFloat("1.555"));
obscure
  • 11,916
  • 2
  • 17
  • 36
2

You need to remove the commas before parsing:

var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));

similiar question on this link Remove commas from the string using JavaScript

J Rui Pinto
  • 354
  • 2
  • 9