2012-07-10 35 views
0

我使用2精度點(即1.38)的十進制數。我想根據以下數字四捨五入:Javascript中的自定義循環數

1)如果第二個精度點大於或等於8(1.38或1.39),則將其四捨五入爲1.4,否則不要改變。

我該如何在Javascript中做到這一點。 toFixed不能很好地工作,因爲它將1.75加到1.8,這不是我想要的。

+1

我認爲你必須將所有的數字轉換成字符串和手動上/下手動... – Lix 2012-07-10 15:02:14

回答

2

繼承人做的一個非常笨拙的方法:

var round = function(n) { 
    var h = (n * 100) % 10; 
    return h >= 8 
     ? n + (10 - h) * .01 
     : n; 
}; 
0

下面是一個簡單的方法:

function customRound(n){ 
    var r = (((n+.02)*10)>>>0)/10; 
    return r>n?r:n; 
} 

console.log(customRound(1.38));// 1.4 
console.log(customRound(1.37999999999));// 1.37999999999 

玩得開心〜