2016-07-04 157 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)

相关问题