常见错误
console.log(0.1+0.2); // 输出 0.30000000000000004
console.log(0.3-0.1); // 输出:0.19999999999999998
console.log(0.07*100); // 输出 7.000000000000001
http://www.css88.com/archives/7340
http://justjavac.com/codepuzzle/2012/11/02/codepuzzle-float-from-surprised-to-ponder.html
http://justjavac.com/codepuzzle/2012/11/11/codepuzzle-float-who-stole-your-accuracy.html
成熟库
- big.js (6kb)
- bignumber.js (18.1kb)
- decimal.js (30.8kb)
- mathjs
其中,前3个是同一个作者,体积一个比一个大,参见作者写的:big.js,bignumber.js和decimal.js有什么区别?
以decimal.js
为例:
new Decimal(0.1).plus(0.2).toString() // '0.3'
new Decimal(0.3).minus(0.1).toString() // '0.2'
new Decimal(0.07).times(100).toString() // '7'
最后一个 mathjs 是比较出名的专门处理数学计算的库,功能非常全,如果只是用来解决精度计算用这个库会显得杀鸡用牛刀。