问题描述
我一直试图用科学记数法计算结果,但仍然禁止无穷大规则,但我似乎无法让它发挥作用。当我使用 toExponential() 函数时,它会响应一条错误消息。请问我有什么帮助吗?代码如下:
<!DOCTYPE html>
<html>
<body>
Base:<input id="n1" rows=1 cols=3 type=number">
Exponent:<input id="n2" rows=1 cols=3 type="number">
<script>
var calc=0
function calculate() {
calc=document.getElementById("result").innerHTML =
BigInt(document.getElementById("n1").value)**BigInt(document.getElementById("n2").value)
calc.toExponential()=document.getElementById("result");
}
</script>
<button onclick="calculate()">Calculate</button><p>=<span id="result" style=display:none></span>
</p>
<script src="decimal.js/decimal.js"></script>
</body>
</html>
解决方法
toExponential 在 BigInt 上不存在。由于toExponential()
中存在Number.prototype.toExponential()
,所以需要将BingInt解析为float,然后调用toExponential()。
function calculate() {
let calc = BigInt(document.getElementById("n1").value)**BigInt(document.getElementById("n2").value);
document.getElementById("result").innerHTML = parseFloat(calc).toExponential();
console.log(parseFloat(calc).toExponential());
}
<!DOCTYPE html>
<html>
<body>
Base:<input id="n1" rows=1 cols=3 type=number">
Exponent:<input id="n2" rows=1 cols=3 type="number">
<button onclick="calculate()">Calculate</button><p>=<span id="result"></span>
</p>
</body>
</html>