# x的10的n次方解决js浮点数计算

## 遇到的问题

``````0.1 + 0.2
//0.30000000000000004

1.4 - 0.3
//1.0999999999999999

19.9 * 100
//1989.9999999999998

24.56 / 100
//0.24559999999999998``````

``````2.235.toFixed(2)
//'2.23'``````

## 解决的办法

``````//加减法，如果需要减就加负数

//乘法
numberFloat.mul(19.9,100,2) //结果3980

//除法
numberFloat.div(19.9,100) //结果0.199

//保留小数
numberFloat.toFixed(2.235, 2) //结果2.24

//格式化
numberFloat.moneyFormat(15243.1456) //结果15,243.15
``````
``````const numberFloat = {
getLength(x) {
let arr = x.toString().split('.')
return arr.length > 1 ? arr[1].length : 0
},
_handleData() {
let args = []
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i])
}
let r = args.map(x => {
return this.getLength(x)
})
const n = Math.max(...r)
//扩大之后的数据
//每一项扩大10的n次方
const c = args.map(x => {
return Number(`\${x}e\${n}`)
})

return { c, n }
},
//加减法, 减法就是加负数
const { c, n } = this._handleData(...arguments)
const reducer = (acc, curr) => acc + curr
let all = c.reduce(reducer, 0)
return all / Number(`1e\${n}`)
},
mul() {
const { c, n } = this._handleData(...arguments)
const reducer = (acc, curr) => acc * curr
let all = c.reduce(reducer, 1)
return all / Number(`1e\${n * arguments.length}`)
},
div() {
const { c } = this._handleData(...arguments)
const reducer = (acc, curr) => acc ? acc / curr : curr
let all = c.reduce(reducer)
return all
},
toFixed(count, n) {
let round = Math.round(`\${count}e\${n}`)
return Number(`\${round}e\${-n}`).toFixed(n)
},
moneyFormat(count) {
let mon = this.toFixed(count, 2)
let reg = /(\d)(?=(\d{3})+\.)/g
return mon.replace(reg, (\$0, \$1) => \$1 + ',')
}
}
``````

65 声望
0 粉丝
0 条评论