2

I'm trying to write an equation within a sum loop and everything works fine by the use of an addition sign +, which I'm assuming is confusing the incrementing of the sum loop. The value should be 56 for the equation but actual output is a string of 095959595.

JFIDDLE

The code looks like this:

$(function () {
    var feature = $('.product');
    var supplier = $('#supplier').val();

    var costCurve = $('#productCostCurve').val();
    var baseCost = $('#baseComponentCost').val();

    var unitCost = 0;

    $.each(feature, function () {
        unitCost += (costCurve * parseFloat($(this).val()) * baseCost * supplier) + baseCost;
    });

    $('#product-cost').html(unitCost);
});

1 Answer 1

4

The problem is baseCost, it is a string value so a string concatenation is done

$(function() {
  var feature = $('.product');
  var supplier = $('#supplier').val();

  var costCurve = $('#productCostCurve').val();
    //use a unary plus or parseFloat to convert this to a numeric value
  var baseCost = +$('#baseComponentCost').val();

  var unitCost = 0;

  $.each(feature, function() {
    unitCost += (costCurve * parseFloat($(this).val()) * baseCost * supplier) + baseCost;
  });

  $('#product-cost').html(unitCost);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="productCostCurve" value="0.5" />
<input type="text" id="baseComponentCost" value="5" />
<input type="text" class="product" value="4" />
<input type="text" class="product" value="4" />
<input type="text" class="product" value="4" />
<input type="text" class="product" value="4" />
<input type="text" id="supplier" value="0.9" />
<div id="product-cost"></div>

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

2 Comments

Shouldn't the supplier and the costCurve have the same issue?
@nem it is used in a multiplication operation which is numeric specific so the conversion will be done automatically... the + operator is used as addition and string concatenation operator

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.