JavaScript百分比计算器加法器功能不起作用

时间:2019-02-13 18:18:20

标签: javascript function percentage

我正在构建一个百分比计算器来学习JavaScript。以下是我的尝试。

其中一个函数可以很好地工作(一个从数字中减去百分比的函数),但是一个将百分比添加到数字中的函数似乎是在添加值,就像它们是字符串一样。我一直在寻找解决方案,并且使用parseInt()似乎可以解决很多问题,但是我似乎无法用当前的代码来实现它,因此希望有人能提供帮助。

function myFunction() {
  var per = document.getElementById("input1").value;
  var num = document.getElementById("input2").value;
  var sum = num / 100 * per;
  var output = num - sum;

  console.log(output);

  document.getElementById("demo").innerHTML = output;

}


function myFunction2() {
  var per = document.getElementById("input3").value;
  var num = document.getElementById("input4").value;
  var sum = num / 100 * per;
  var output = sum + num;

  console.log(output);

  document.getElementById("demo1").innerHTML = output;

}
<section id="number less percentage"></section>

<h1>Number less percentage</h1>

<input id="input2" placeholder="enter the number"></input>

<input id="input1" placeholder="enter percentage of a number"></input>

<button value='send' id="submit" onclick="myFunction()">Click for 
    result</button>

<p id="demo"></p>

</section>

<section id="number plus percentage"></section>

<h1>Number plus percentage</h1>

<input id="input4" placeholder="enter the number"></input>

<input id="input3" placeholder="enter percentage of a number"></input>

<button value='send' id="submit" onclick="myFunction2()">Click for 
    result</button>

<p id="demo1"></p>

</section>

1 个答案:

答案 0 :(得分:1)

JavaScript在涉及数字和加法时有点有趣。例如:

'20' - '30' === 10      // `-` always coerces operands to numbers
'20' + '30' === '2030'  // `+` with strings is interpreted as concatenation

document.getElementById返回的值是字符串,因此最好在继续加法或减法之前将它们 all (甚至是可行的)解析为数字。您的代码可以是:

function calculate() {
  var per = parseInt(document.getElementById('input1').value);
  var num = parseInt(document.getElementById('input2').value);

  var sum = (num / 100) * per;
  var output = num - sum;

  console.log(output);

  document.getElementById('demo').innerHTML = output;
}

function myFunction2() {
  var per = parseInt(document.getElementById('input3').value);
  var num = parseInt(document.getElementById('input4').value);

  var sum = (num / 100) * per;
  var output = sum + num;

  console.log(output);

  document.getElementById('demo1').innerHTML = output;
}