解决js计算 小数加减乘除失真的功能函数

function floatPoint(one, two, str) {
    //转化为字符串
    one = '' + one
    two = '' + two
    //切割成整数部分和小数部分
    var oneStr = one.split('.')
    var twoStr = two.split('.')


    // 处理参数一或二为整数的情况
    if (!oneStr[1]) {
        oneStr[1] = '0'
    }
    if (!twoStr[1]) {
        twoStr[1] = '0'
    }

    var length = null
    //比较小数部分的长度,以确定剥离小数点后放大的倍数
    var oneFloatLength = oneStr[1].length
    var TwoFloatLength = twoStr[1].length
    if (oneFloatLength > TwoFloatLength) {
        length = oneFloatLength
        twoStr[1] = twoStr[1].padEnd(length, '0')
    } else if (TwoFloatLength > oneFloatLength) {
        length = TwoFloatLength
        oneStr[1] = oneStr[1].padEnd(length, '0')
    } else {
        length = TwoFloatLength
    }
  oneStr[1] = oneStr[1].replace(/^0+/g,'')
   twoStr[1] = twoStr[1].replace(/^0+/g,'')
    // 拼接成处理后的数字
    var oneBig = (oneStr[0] === '0' ? '' : oneStr[0]) + oneStr[1]
    var twoBig = (twoStr[0] === '0' ? '' : twoStr[0]) + twoStr[1]

    //根据运算符决定运算后缩小的倍数
    var result = null
    console.log(oneBig + str + twoBig)
    switch (str) {
        case '+':
            ;
        case '-':
            result = eval(oneBig + str + twoBig) / (10 ** length)
            break;
        case '*':
            result = eval(oneBig + str + twoBig) / (10 ** (length * 2))
            break;
        case '/':
            result = eval(oneBig + str + twoBig)
    }
    return result
}

简单的小函数,只做了+ 、- 、* 、/四则运算,第一、二个参数为参与运算的两个数,第三个参数为运算符(+-*/),

思路是运算前用字符串处理拿掉 '.' ,运算结束后还原倍数。

posted @ 2018-12-01 15:01  superjsman  阅读(1345)  评论(0编辑  收藏  举报