javascript - 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
解决方案
这是因为您尝试将字符串添加到数字。您需要转换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>
推荐阅读
- angular - 关于 controlArray.push(new FormGroup) 无法启用() 之前的表单组控件
- android - 在 android R 中替换 BUILD_BROKEN_PHONY 和 phony-rebuild
- c++ - C++:实现公共接口函数,作为私有
- java - 如何根据用户输入管理加减值?
- python - 使用重采样数据和宽度 = 1 绘制条形图以及如何避免“将整数和整数数组加/减到时间戳”?
- sql - 有没有办法在 ID 主键中创建另一个值?
- apache-calcite - 自定义 Calcite 的 Sql 解析器
- python - 'xml.etree.ElementTree.ParseError: no element found' 制作 python 类时
- python - 如何防止使用 os.listdir 将相同的文件添加到列表中?
- angular - spring 无法从角度请求中接收 csrf 令牌