2016-07-04 156 views
0

lodash對我來說產生了意想不到的行爲。如果我指定四捨五入到小數點後兩位,有時會給我一個。這是lodash v3.20.1和Chrome v51。例如5.599999將舍入到5.6而不是5.59。lodash舍入到小數點後1位而不是2

var num = 5.58888 
console.log('lodash num .round is ' + _.round((num), 2)); // 5.59 as expected 

var num2 = 5.59999; 
console.log('lodash num2 .round is ' + _.round((num2), 2)); // 5.6 not expected, why? 

這是錯誤還是我做錯了什麼?

+2

'5.59'不是'5.59999'四捨五入至小數點後兩位。它確實是'5.6'。你還需要'5.60'嗎?然後使用'toFixed'。 – Xufox

回答

3

由於@Xufox解釋說:

5.59被四捨五入至小數點後2位5.60

但隨着尾隨零一些不添加任何精度,也沒有必要表現出來,它的自動除去。 如果你需要強制它,你可以使用toFixed()方法,它使用定點表示法來格式化一個數字。

_.round((num2), 2).toFixed(2)) //lodash num2 .round is 5.60 

考慮到它返回_.round結果的字符串表示((NUM2),2)

相關問題