如何使用JavaScript正确支持小数输入以修复加密货币价格计算器
加密货币最高价格计算器问题修复
问题根源
输入小数无返回的问题确实由parseInt导致:parseInt仅会解析输入内容的整数部分,输入小数时如果数值小于1(例如0.8)会直接返回0,触发if(numOne && numTwo && numThree)的判断拦截,自然不会返回计算结果。
同时现有代码还存在一处逻辑顺序错误:先把res赋值给结果输入框,再计算res的实际值,会导致第一次点击计算看不到结果,第二次点击才会显示上一次的计算值。
修复方案
- 将所有
parseInt替换为parseFloat,该方法支持解析小数格式的数值 - 调整计算逻辑顺序,先计算
res的值再赋值给结果输入框
修复后完整代码
JavaScript 代码
var numOne, numTwo, numThree, res, temp; function crypto() { numOne = parseFloat(document.getElementById("one").value); numTwo = parseFloat(document.getElementById("two").value); numThree = parseFloat(document.getElementById("three").value); if(numOne && numTwo && numThree) { temp = document.getElementById("res"); temp.style.display = "block"; res = (numOne / numTwo) * numThree; document.getElementById("calc").value = res; } }
HTML 代码
<p id="input">Enter Bitcoin Marketcap: <input id="one"> <br/><br/> Enter Target Marketcap: <input id="two"></p> Enter Current Price per One Target Coin: <input id="three"></p> <p><button onclick="crypto()">Calculate max price per one cryptocoin</button></p> <p id="res" style="display:none;"> Price Per Coin Result = <input id="calc"><br/><br/>
内容的提问来源于stack exchange,提问作者Allie Johnson
相关产品推荐
相关产品推荐

