【问题标题】:How to round "p.value" js to the closest even number如何将“p.value”js四舍五入到最接近的偶数
【发布时间】:2017-07-11 06:36:56
【问题描述】:

在我的网站上有一个简单的计算器,可以将 6000 除以某个数字

<form oninput="p.value = 6000 / parseFloat(rpms.value)">
<input type="number" id="rpms" >
<input type="number" id="p" name="Number" disabled> 

请帮我将第二个输入字段的p.value四舍五入到最接近的偶数。

我希望它是整数,没有任何小数位

提前谢谢你!

我进行了几次搜索,但是...我是 JS 的绝对业余爱好者,不知道在哪里以及如何将它放在 html 代码中。

但是我设法做到了: oninput="p.value = parseInt(6000 / parseFloat(rpms.value))"

但后来我记得这个公式中只允许使用偶数,它计算感应电机的极数。

所以,请帮我四舍五入到最接近的偶数。

【问题讨论】:

  • 使用 Math.round(number);
  • 一个简单的搜索会告诉你至少 100 种方法!?
  • 我做了几次搜索,但是......我对 JS 绝对是个业余爱好者,不知道在哪里以及如何将它放在 html 代码中。但是我设法这样做: oninput="p.value = parseInt(6000 / parseFloat(rpms.value))" 但后来我记得这个公式中只允许使用偶数,它计算感应极数马达。所以,请帮我四舍五入到最接近的偶数。

标签: rounding calculator


【解决方案1】:

方法如下:

function roundToEven(value) {
  return Number.isNaN(n)
    ? 0.0
    : 2 * Math.round(value / 2);
}

/**
 * Round-to-even with a fixed number of decimals (2 decimals = to cent/öre). Returns [ rounded value, formatted rounded value ].
 * @param {*} n The number to round-to-even, with the given number of decimals
 * @param {*} decimals The number of decimals in base10 to round the number at.
 */
function roundToEvenFixed(n, decimals = 2.0) {
  if (Number.isNaN(n) || Number.isNaN(decimals)) {
    return 0.0
  }

  const value = (Math.round((n * Math.pow(10, decimals)) / 2) * 2) / Math.pow(10, decimals),
        formatted = value.toFixed(decimals);

  return [ value, formatted ]
}

当您想要无偏舍入时非常有用。用法:

console.log(`Amount: ${roundToEvenFixed(i.quantity * i.unitPrice.amount)[1]} kr`)

参考

【讨论】:

    【解决方案2】:

    Javascript 正在为该任务提供Math.round(x)

    p.value = Math.round(6000 / parseFloat(rpms.value));
    

    其他例子

    Math.round(170.68); // return 171
    Math.round(171.32); // return 171
    

    【讨论】:

    • 抱歉,他想将值四舍五入到最接近的偶数。
    • @teo 感谢您的通知。
    • 这是错误的;该问题要求四舍五入到最接近的偶数
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多