JS清除浮点数的方法

话不多说直接上代码:

首先,思路是把小数化为整数进行运算再变成小数

第一步:需要知道小数点后面有几位小数

function digitLength(e) {

            var e1 = (e + '').split('');//把数值转为字符串,然后转为数组方便获取小数点的索引

            var e2 = e1.findIndex((item) => item = '.')

            return e1.length - 1 - e2;//小数点后面几位

        }

第二步:就是化整运算,再化为小数

加法运算:

function  add(a, b) {

两种情况:一种是a小数点后面位数比较多b

        var as = Math.pow(10, digitLength(a))//两个数的最小公倍数

另一种是b小数点后面位数比较多

        var as2 = Math.pow(10, digitLength(b))//两个数的最小公倍数

        if (digitLength(a) >= digitLength(b)) {

            return (as * a + as * b) / as

        } else {

            return (as2 * a + as2 * b) / as2

        }

        function digitLength(e) {

            var e1 = (e + '').split('');

            var e2 = e1.findIndex((item) => item = '.')

            return e1.length - 1 - e2;

        }

    }

减法运算 (加法运算跟加法一样)

function sub(a, b) {

        var as = Math.pow(10, digitLength(a))

        var as2 = Math.pow(10, digitLength(b))

        if (digitLength(a) >= digitLength(b)) {

            return (as * a - as * b) / as

        } else {

            return (as2 * a - as2 * b) / as2

        }

        function digitLength(e) {

            var e1 = (e + '').split('');

            var e2 = e1.findIndex((item) => item = '.')

            return e1.length - 1 - e2;

        }

    }

乘法运算

function mul(a, b) {

        var as = Math.pow(10, digitLength(a))

        var as2 = Math.pow(10, digitLength(b))

        if (digitLength(a) >= digitLength(b)) {

            return (as * a * as * b) / as / as//这里要除以最小公倍数的平方

        } else {

            return (as2 * a * as2 * b) / as2 / as2

        }

        function digitLength(e) {

            var e1 = (e + '').split('');

            var e2 = e1.findIndex((item) => item = '.')

            return e1.length - 1 - e2;

        }

    }

除法运算

 function bed(a, b) {

        var as = Math.pow(10, digitLength(a))

        var as2 = Math.pow(10, digitLength(b))

        if (digitLength(a) >= digitLength(b)) {

            return ((as * a) / (as * b))

        } else {

            return ((as2 * a) / (as2 * b))

        }

        function digitLength(e) {

            var e1 = (e + '').split('');

            var e2 = e1.findIndex((item) => item = '.')

            return e1.length - 1 - e2;

        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值