Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash rounding to 1 decimal place instead of 2

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?

like image 579
Phil Avatar asked Nov 30 '22 09:11

Phil


1 Answers

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)

like image 108
andybeli Avatar answered Dec 23 '22 08:12

andybeli