【问题标题】:Math.round doesn't work in JavaScriptMath.round 在 JavaScript 中不起作用
【发布时间】:2015-09-09 06:25:07
【问题描述】:

代码运行良好,直到我在函数内添加该行

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>

【问题讨论】:

  • 你能解释一下你想做什么吗?
  • 在你的函数中:Math.round return Number,你尝试做 toString 替换分隔符,然后再次尝试获取相同的 Number,但是为什么???如果你这样做return Math.round(num*1.2) 结果将是相同的
  • 另见post

标签: javascript jquery html


【解决方案1】:
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(), '.'));
}

【讨论】:

  • 在这种情况下也可能使用toFixed而不是Math.round
  • @Grundy:这是这里 许多 可能的改进之一 ;-) 我不确定 OP 到底想用这段代码做什么。
  • 是的,在这个函数中也是 OP 传递字符串,所以它也可以返回一个 NaN,我认为 :-)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2021-08-14
    • 2018-07-06
    • 2018-07-07
    • 2012-07-01
    相关资源
    最近更新 更多