从表单输入中获取数字时丢失十进制值

我正在尝试从 HTML 表单输入中获取一个值(最多 2 位小数),然后我计划将该值用于 JavaScript 中的某些计算。


我遇到的问题是当用户输入一个值时,小数位会丢失。


我简化了下面的代码以突出显示该问题。


<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<body>

  <form>

    1st Number<br> <input type="number" step="0.01" id="num1" placeholder=0.00>

  </form>


  <button onclick="calculator()">submit</button>


  <p id="answer"></p>

</body>


<script>

        function calculator(){

            const num1 = document.getElementById("num1").value|0;

            document.getElementById("answer").innerHTML = num1; 

//example user inputs 5.55, the returned value = 5

        }

</script>

</html>


慕田峪9158850
浏览 90回答 2
2回答

繁星点点滴滴

您没有为逻辑或使用正确的运算符,这是||(逻辑)不是|(按位)。此外,您应该使用.textContentinstead of.innerHTML将值设置到另一个元素中,因为检索到的值不包含任何 HTML。.innerHTML具有安全和性能影响。<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; <title>Document</title></head><body>&nbsp; <form>&nbsp; &nbsp; 1st Number<br> <input type="number" step="0.01" id="num1" placeholder=0.00>&nbsp; </form>&nbsp; <button onclick="calculator()">submit</button>&nbsp; <p id="answer"></p></body><script>&nbsp; &nbsp; &nbsp; &nbsp; function calculator(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const num1 = document.getElementById("num1").value || 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("answer").textContent = num1;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }</script></html>

森林海

您正在使用二元运算符将值转换为 int(内部)。您应该改为parseFloat或使用+运算符将其转换为Number<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; <title>Document</title></head><body>&nbsp; <form>&nbsp; &nbsp; 1st Number<br> <input type="number" step="0.01" id="num1" placeholder=0.00>&nbsp; </form>&nbsp; <button onclick="calculator()">submit</button>&nbsp; <p id="answer"></p></body><script>&nbsp; &nbsp; &nbsp; &nbsp; function calculator(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const num1 = parseFloat(document.getElementById("num1").value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("answer").innerHTML = num1;&nbsp;//example user inputs 5.55, the returned value = 5&nbsp; &nbsp; &nbsp; &nbsp; }</script></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript