Plus operator in JavaScript doesn't sum my values

前端 未结 4 1742
深忆病人
深忆病人 2021-01-28 22:57

I\'m trying to calculate the number of payments but output was wrong so i tried to calculate a simple operation on the month value.But \"+\" operator doesn\'t sum my values it a

相关标签:
4条回答
  • 2021-01-28 23:17

    The actual type of the value is string. That's why string concatenation is happening. You have to use parseInt to convert string to integer to perform intended arithmetic operation.

    Change:

    var months=(principal)+(interestrate);

    To:

    var months = parseInt(principal) + parseInt(interestrate);

    0 讨论(0)
  • 2021-01-28 23:19

    The values you are summing are strings. You need to convert them to integers:

    parseInt(principal)+parseInt(interestate)
    

    The reason for this is that input values are always strings. AFAIK, this is even if you set the type to number. parseInt(s) converts a string s to an int.

    0 讨论(0)
  • 2021-01-28 23:21
    var months=parseInt(principal)+parseInt(interestrate);
    

    Values need to be converted to an integer first.

    0 讨论(0)
  • 2021-01-28 23:21

    Your input values are treated as string as they are textbox inputs. Parse the values first before adding them up.

    e.g.

    var principal = parseInt(princ.value); var interestrate = parseInt(interest.value);

    0 讨论(0)
提交回复
热议问题