Javascript FAQ

Javascript FAQ

Float precision

1
console.log(0.1 + 0.2) // 0.30000000000000004

Solution: Strip

1
2
3
4
5
function strip(number) {
return parseFloat(number.toFixed(12));
}

console.log(strip(0.1 + 0.2)) // 0.3

Solution: Decimal.js

  • The decimal.js package is 283kb at the time of writing. So decimal.js is not appropriate for frontend.
1
2
3
4
5
const Decimal = require('decimal.js')

let m = new Decimal(0.1)

console.log(m.add(0.2).toNumber()) // 0.3
Author

Chendongtian

Posted on

2023-03-20

Updated on

2023-08-04

Licensed under

Comments