繁体   English   中英

Math.round在JavaScript中不起作用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM