[英]Math.round doesn't work in JavaScript
代碼工作正常,直到我在函數內添加行
parseLocalFloatCnt: num = Math.round(num*1.2);
有誰知道如何解決這個問題? 謝謝
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="myInput" oninput="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
var x = parseLocalFloatCnt(document.getElementById("myInput").value);
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
function parseLocalFloatCnt(num) {
num = Math.round(num*1.2);
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
</script>
</body>
</html>
Uncaught TypeError: num.replace is not a function(…)
您無法在號碼上撥打replace
號碼。
你可以這樣做:
function parseLocalFloatCnt(num) {
num = Math.round(num*1.2) + ''; // convert `num` to string
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
不要忘記num to.String();
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="myInput" oninput="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
var x = parseLocalFloatCnt(document.getElementById("myInput").value);
document.getElementById("demo").innerHTML = "You wrote: " + x;
}
function parseLocalFloatCnt(num) {
num = Math.round(num*1.2).toString();
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.