如何将“p.value”js舍入到最接近的偶数

时间:2017-07-11 06:36:57

标签: rounding calculator

在我的网站上有一个简单的计算器,它在一定数量上除以6000

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

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

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

提前谢谢!

我做了几次搜索,但是......我绝对是业余爱好者,不知道在哪里以及如何把它放在HTML代码中。

但是我设法做到这样: oninput =“p.value = parseInt(6000 / parseFloat(rpms.value))”

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

所以,请帮我把它舍入到最近的偶数。

2 个答案:

答案 0 :(得分:0)

方法如下:

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`)

参考

答案 1 :(得分:-1)

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

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

其他例子

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