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
  • 2 5.59 isn’t 5.59999 rounded to two decimal places. It’s indeed 5.6. Do you still need 5.60? Then use toFixed. – Sebastian Simon Commented Jul 4, 2016 at 16:14
Add a comment  | 

1 Answer 1

Reset to default 28

As @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