首页 > 解决方案 > JavaScript 计算器写入错误的数字

问题描述

我在这段代码中有一个小错误,请帮助我。

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, 
    maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <input type="text" id="price">
  <button onclick="calc()">GO</button>
  <h1 id="show"></h1>
  <script type="text/javascript">
    function calc() {
      "use strict";
      var price = document.getElementById('price').value;
      var res = (price / 100 * 5 + 20) + price;
      var show = document.getElementById('show').value = Math.floor(res);
    }
  </script>
</body>
</html>

例如:输入 100 结果是 10025,我需要 125

标签: javascripthtmlcalculator

解决方案


这是因为您尝试将字符串添加到数字。您需要转换price为这样的数字:

var price = parseFloat(document.getElementById('price').value);
// Or like this :
var price = Number(document.getElementById('price').value);
// Or like this :
var price = document.getElementById('price').value * 1;

显示十进制数字的完整示例:

var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');

function calc() {
  var price = parseFloat(priceElement.value, 10);
  var result = (price / 100 * 5 + 20) + price;
  showElement.innerHTML = result.toFixed(2);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>


推荐阅读