-1

I am trying to do a credit calculator and when I try to add sum value with resultat I get a result $ 30060 instead of $ 360. Why is let resultat not adding sum and text together?

function result() {

const sum = document.getElementById('sum').value;
const percent = document.getElementById('percentage').value;
const months = document.getElementById('months').value;


let text = sum * (percent / 100 ) * months;
let resultat = sum + text;
  console.log(resultat);
    return document.getElementById('result').innerHTML = '$ ' + resultat;

}
<div>

<input type="text" id="sum" placeholder="Enter sum..$">
<input type="text" id="percentage" placeholder="Enter %..">
<input type="text" id="months" placeholder="Enter months..">
<button id="calculate" onClick="result()">
Calculate
</button><br><br>
To payback:
<p id="result">
 </p>

</div>
Dave
  • 1
  • 1
  • 9
  • 38
  • 3
    `document.getElementById('sum').value` is returning a **string** I assume. Use [`Number()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) to convert. – norbitrial Sep 14 '20 at 13:10

1 Answers1

1

Since the inputs are storing and returning those numbers as strings, you can use parseFloat to convert them to numbers before using them for math:

function result() {

const sum = parseFloat(document.getElementById('sum').value);
const percent = parseFloat(document.getElementById('percentage').value);
const months = parseFloat(document.getElementById('months').value);


let text = sum * (percent / 100 ) * months;
let resultat = sum + text;
  console.log(resultat);
    return document.getElementById('result').innerHTML = '$ ' + resultat;

}
<div>

<input type="text" id="sum" placeholder="Enter sum..$">
<input type="text" id="percentage" placeholder="Enter %..">
<input type="text" id="months" placeholder="Enter months..">
<button id="calculate" onClick="result()">
Calculate
</button><br><br>
To payback:
<p id="result">
 </p>

</div>
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45