Javascript舍入到最接近的2位小数(但是5舍入)

时间:2014-10-09 01:21:41

标签: javascript math rounding

我的所有值都从服务器返回3位小数。我需要舍入到最近的10,2位小数,例如。十进制的十进制(18,2)(18,3)。问题是,当它是5时,它需要向下舍入。

我需要在JavaScript中执行此操作:D

我不能保证会返回3个小数位,即最大值。

ex. 4.494 -> 4.49

**ex. 4.495 -> 4.49**

ex. 4.496 -> 4.50

2 个答案:

答案 0 :(得分:1)

看起来你只想在最后一个数字是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

答案 1 :(得分:0)

也许创建自己的自定义轮功能?看看Is it ok to overwrite the default Math.round javascript functionality?

鉴于上述帖子中的解决方案,您可以稍微修改它:

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