admin管理员组文章数量:1188441
lodash is, for me, producing unexpected behaviour. Where I'm specifiying rounding to 2 decimal places sometimes gives me one. This is lodash v3.20.1 and Chrome v51. For example 5.599999 will round to 5.6 instead of 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?
Is this is bug or am I doing something wrong?
lodash is, for me, producing unexpected behaviour. Where I'm specifiying rounding to 2 decimal places sometimes gives me one. This is lodash v3.20.1 and Chrome v51. For example 5.599999 will round to 5.6 instead of 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?
Is this is bug or am I doing something wrong?
Share Improve this question asked Jul 4, 2016 at 16:03 PhilPhil 3,7363 gold badges35 silver badges42 bronze badges 1 |1 Answer
Reset to default 28As @Xufox explained:
5.59 is rounding to 2 decimal places 5.60
But a number with trailing zeros doesn't add any precision, there is no need to show it, it's automatically removed. If you need to force it, you can use the toFixed() method which formats a number using fixed-point notation.
_.round(num2, 2).toFixed(2) // lodash num2 .round is 5.60
Take into account that it returns a string representation of the result of _.round(num2, 2)
本文标签: javascriptlodash rounding to 1 decimal place instead of 2Stack Overflow
版权声明:本文标题:javascript - lodash rounding to 1 decimal place instead of 2 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738395766a2084496.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
5.59
isn’t5.59999
rounded to two decimal places. It’s indeed5.6
. Do you still need5.60
? Then usetoFixed
. – Sebastian Simon Commented Jul 4, 2016 at 16:14