对我来说,lodash 会产生意想不到的行为。我指定四舍五入到小数点后两位的地方有时会给我一个。这是 lodash v3.20.1 和 Chrome v51。例如,5.599999 将四舍五入为 5.6 而不是 5.59。

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?

这是错误还是我做错了什么?

最佳答案

正如 @Xufox 解释的那样:

5.59 四舍五入到小数点后两位 5.60

但是带有尾随零的数字不会增加任何精度,不需要显示它,它会自动删除。
如果需要强制执行,可以使用 toFixed() 方法,该方法使用定点表示法格式化数字。

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

考虑到它返回 _.round(num2, 2) 结果的字符串表示

关于javascript - lodash 四舍五入到小数点后 1 位而不是 2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38188692/

10-13 09:26