简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM