Math.round在JavaScript中不起作用

时间:2015-09-09 06:25:07

标签: javascript jquery html

代码工作正常,直到我在函数

中添加行
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>

2 个答案:

答案 0 :(得分:3)

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(), '.'));
}

答案 1 :(得分:0)

不要忘记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>