繁体   English   中英

JavaScript计算器写错数字

[英]JavaScript calculator writes wrong number

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

<!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

这是因为您尝试将字符串添加到数字中。 您需要将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> 

在那里。


一些修复:

将元素存储在函数之外,因为在您的情况下,它们的id不会更改:

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

使用parseFloat(...)解析存储在字符串中的浮点数:

var price = parseFloat(priceElement.value);

要设置元素的内容(在您的情况下,是h1元素的内容),请使用.innerHTML

showElement.innerHTML = Math.floor(result);

 var priceElement = document.getElementById('price'); var showElement = document.getElementById('show'); function calc() { var price = parseFloat(priceElement.value); var result = (price / 100 * 5 + 20) + price; showElement.innerHTML = Math.floor(result); } 
 <input type="text" id="price"> <button onclick="calc()">GO</button> <h1 id="show"></h1> 

是的,price的值为字符串,因此将其转换为数字。
而且我认为您的“ document.getElementById('show')。value”没有用。
并且不使用变量show。
res的公式有些复杂-请参阅var v1。
也许您会发现使用console.log在调试中很有用。

<html>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
  "use strict";
function calc() {
  var price = 1*document.getElementById('price').value;
  console.log("price", price);
  var res = (price / 100 * 5 + 20) + price;
  console.log("res", res);
  document.getElementById('show').innerHTML = Math.floor(res);
  var v1 = price*1.05 + 20;
  console.log("v1", v1);
  document.getElementById('show').innerHTML += ", " + v1;
}
</script>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM