function fix(number,m){ //公式,保留几位小数 return Math.round( Math.pow(10,m)*number )/Math.pow(10,m) } console.log( fix((0.3-0.1),2) )
————————————————-
console.log(0.1+0.2); // 输出 0.30000000000000004 console.log(0.3-0.1); // 输出:0.19999999999999998 console.log(0.07*100); // 输出 7.000000000000001
使用第三方库解决:
- 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 是比较出名的专门处理数学计算的库,功能非常全,如果只是用来解决精度计算用这个库会显得杀鸡用牛刀。

http://blog.haoji.me/js-float.html