gpt4 book ai didi

javascript - toExponential() 方法不起作用

转载 作者:行者123 更新时间:2023-11-30 12:05:22 25 4
gpt4 key购买 nike

toExponential() 方法在我的代码中不起作用。chrome 控制台出现此错误:未捕获的类型错误:number.toExponential 不是函数。这是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JS Code Academy</title>
</head>
<body>

<input type="number" id="myInput" value="2.326">

<button id="myButton">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>


<script type="text/javascript">
document.getElementById("myButton").onclick = function() {

var number = document.getElementById("myInput").value;
var str = number.toExponential(2);

document.getElementById("demo1").innerHTML = str;
document.getElementById("demo2").innerHTML = typeof str;
};
</script>


</body>
</html>

最佳答案

toExponential 是在数字类上定义的方法。因此,请确保您使用的是数字而不是字符串:

var value = document.getElementById("myInput").value;
var number = parseFloat(value);
if (!isNaN(number)) {
// The string value entered in the textbox was successfully parsed to a number
// we can now calculate the exponential:
var str = number.toExponential(2);
}

关于javascript - toExponential() 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35382192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com