首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript计算器写入错误的数字

JavaScript计算器写入错误的数字
EN

Stack Overflow用户
提问于 2018-07-02 07:27:07
回答 2查看 295关注 0票数 0

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

代码语言: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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-02 07:31:27

这是因为您尝试将字符串添加到数字中。您需要将price转换为如下所示的数字:

代码语言:javascript
复制
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;

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

代码语言:javascript
复制
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);
}
代码语言:javascript
复制
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>

票数 1
EN

Stack Overflow用户

发布于 2018-07-02 08:08:42

可以,价格的值为字符串,请将其转换为数字。

我不认为你的"document.getElementById('show').value“有用。

并且没有使用变量show。

res的公式有点复杂--参见var v1。

也许你会发现使用console.log在调试中很有用。

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51127697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档