小数加法

2020-04-23  本文已影响0人  liyinkan

众所周知的原因,0.1 + 0.2 = 0.30000000000000004

解决这个问题,最佳方法:使用库
可选择的很多

有小伙伴说在大多数场景可以 *100 再 /100 搞定
现实情况是:GG

console.log(18.9 * 100)
// 1889.9999999999998

10分钟造了个轮子,至少目前自己项目够用

let plus = (a, b) => {
    let findDecimal = (x) => {
        let arr = ('' + x).split('.')
        if (arr.length > 2) {
            throw 'not invliad number'
        }
        return arr.length == 1 ? 0 : arr[1].length
    }
    let toInteger = (x, d) => {
        return +(x.toFixed(d).replace('.', ''))
    }
    let aDecimal = findDecimal(a)
    let bDecimal = findDecimal(b)
    let dec = aDecimal > bDecimal ? aDecimal : bDecimal
    return (toInteger(a, dec) + toInteger(b, dec)) / Math.pow(10, dec)
}

原理上是字符串移动小数点操作。
没啥技术含量,够用就好。

看了眼 Java BigDecimal 的实现,实际上是把一个数字的表示变成了两部分

上一篇下一篇

猜你喜欢

热点阅读