解决js Number类型计算浮点数问题

caculation.js

var countDecimals = function(num) {

    var len = 0;

    try {

        num = Number(num);

        var str = num.toString().toUpperCase();

        if (str.split('E').length === 2) { // scientific notation

            var isDecimal = false;

            if (str.split('.').length === 2) {

                str = str.split('.')[1];

                if (parseInt(str.split('E')[0]) !== 0) {

                    isDecimal = true;

                }

            }

            let x = str.split('E');

            if (isDecimal) {

                len = x[0].length;

            }

            len -= parseInt(x[1]);

        } else if (str.split('.').length === 2) { // decimal

            if (parseInt(str.split('.')[1]) !== 0) {

                len = str.split('.')[1].length;

            }

        }

    } catch (e) {

        throw e;

    } finally {

        if (isNaN(len) || len < 0) {

            len = 0;

        }

        return len;

    }

};

var convertToInt = function(num) {

    num = Number(num);

    var newNum = num;

    var times = countDecimals(num);

    var temp_num = num.toString().toUpperCase();

    if (temp_num.split('E').length === 2) {

        newNum = Math.round(num * Math.pow(10, times));

    } else {

        newNum = Number(temp_num.replace(".", ""));

    }

    return newNum;

};

var getCorrectResult = function(type, num1, num2, result) {

    var temp_result = 0;

    switch (type) {

        case "add":

            temp_result = num1 + num2;

            break;

        case "sub":

            temp_result = num1 - num2;

            break;

        case "div":

            temp_result = num1 / num2;

            break;

        case "mul":

            temp_result = num1 * num2;

            break;

    }

    if (Math.abs(result - temp_result) > 1) {

        return temp_result;

    }

    return result;

};

export default {

    //加法

    accAdd(num1, num2) {

        num1 = Number(num1);

        num2 = Number(num2);

        var dec1, dec2, times;

        try { dec1 = countDecimals(num1) + 1; } catch (e) { dec1 = 0; }

        try { dec2 = countDecimals(num2) + 1; } catch (e) { dec2 = 0; }

        times = Math.pow(10, Math.max(dec1, dec2));

        // var result = (num1 * times + num2 * times) / times;

        var result = (this.accMul(num1, times) + this.accMul(num2, times)) / times;

        return getCorrectResult("add", num1, num2, result);

        // return result;

    },

    //减法

    accSub(num1, num2) {

        num1 = Number(num1);

        num2 = Number(num2);

        var dec1, dec2, times;

        try { dec1 = countDecimals(num1) + 1; } catch (e) { dec1 = 0; }

        try { dec2 = countDecimals(num2) + 1; } catch (e) { dec2 = 0; }

        times = Math.pow(10, Math.max(dec1, dec2));

        // var result = Number(((num1 * times - num2 * times) / times);

        var result = Number((this.accMul(num1, times) - this.accMul(num2, times)) / times);

        return getCorrectResult("sub", num1, num2, result);

        // return result;

    },

    //除法

    accDiv(num1, num2) {

        num1 = Number(num1);

        num2 = Number(num2);

        var t1 = 0,

            t2 = 0,

            dec1, dec2;

        try { t1 = countDecimals(num1); } catch (e) {}

        try { t2 = countDecimals(num2); } catch (e) {}

        dec1 = convertToInt(num1);

        dec2 = convertToInt(num2);

        var result = this.accMul((dec1 / dec2), Math.pow(10, t2 - t1));

        return getCorrectResult("div", num1, num2, result);

        // return result;

    },

    //乘法

    accMul(num1, num2) {

        num1 = Number(num1);

        num2 = Number(num2);

        var times = 0,

            s1 = num1.toString(),

            s2 = num2.toString();

        try { times += countDecimals(s1); } catch (e) {}

        try { times += countDecimals(s2); } catch (e) {}

        var result = convertToInt(s1) * convertToInt(s2) / Math.pow(10, times);

        return getCorrectResult("mul", num1, num2, result);

        // return result;

    }

}

在 main.js中引用


import cal from './plugins/calculation'

Vue.prototype.cal = cal

调用方法


//减法

this.cal.accSub(2.4,0.8);

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,144评论 1 32
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,315评论 0 3
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,736评论 1 45
  • # 第一级标题 ## 第二级标题 `<h2>` ### 第三级标题 ` ` #### 第二四级标题 ` ` ###...
    SecondChoice阅读 161评论 0 0
  • 丰富多彩的生活使我们明白,道德和美学意义上的美,是生存的目的;善良、爱和艺术上的满足是实现它的形式。道德和美学的美...
    教育小札阅读 112评论 0 0