Javascript四舍五入到最接近的小数点后2位(但向下五舍五入)

Javascript Rounding to the nearest 2 decimal (however 5 rounds down)

本文关键字:2位 四舍五入 最接近 小数点 Javascript      更新时间:2023-09-26

所有我的值都以小数点后3位的形式从服务器返回。我需要四舍五入到最接近的10,2位小数,例如十进制(18,3)中的十进制(18,2)。问题是,当它是5时,它需要四舍五入。

我需要在JavaScript:D中这样做

我不能保证会返回小数点后3位,这是最大值。

ex. 4.494 -> 4.49
**ex. 4.495 -> 4.49**
ex. 4.496 -> 4.50

似乎你只想在最后一个数字是5的地方进行特殊舍入,所以测试一下,并对这些情况进行不同的舍入:

function myRound(n) {
  // If ends in .nn5, round down
  if (/'.'d'd5$/.test(''+n)) {
    n = Math.floor(n*100)/100;
  }
  // Apply normal rounding
  return n.toFixed(2);
}
console.log(myRound(4.494));  // 4.49
console.log(myRound(4.495));  // 4.49
console.log(myRound(4.496));  // 4.50

也许可以创建自己的自定义圆形函数?检查是否可以覆盖默认的Math.round javascript功能?

考虑到上面文章中的解决方案,您可能会稍微修改如下:

Number.prototype.round = function(precision) {
    var numPrecision = (!precision) ? 0 : parseInt(precision, 10);
    var numBig = this * Math.pow(10, numPrecision);
    var roundedNum;
    if (numBig - Math.floor(numBig) == 0.5)
        roundedNum = (Math.round(numBig) + 1) / Math.pow(10, numPrecision);
    else
        roundedNum = Math.round(numBig) / Math.pow(10, numPrecision);
    return roundedNum;
};
var n = 2.344;
var x = n.round(2);
alert(x);