2014-10-09 216 views
-1

我的所有數值都從服務器返回爲3位小數。我需要四捨五入到最接近的10位和2位小數位,例如。十進制(18,3)的十進制(18,2)。問題在於,當它是5時,它需要向下取整。JavaScript舍入到最接近的2位小數(然而5舍入)

我需要做到這一點在JavaScript:d

我不能保證3位小數將被退回,這是最大的。

ex. 4.494 -> 4.49 

**ex. 4.495 -> 4.49** 

ex. 4.496 -> 4.50 
+0

你嘗試過什麼嗎? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round,'if(Math.abs(num)=== 5)'+'Math.floor' should掩蓋你的數字是5的情況 – 2014-10-09 01:30:08

回答

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