2、JS可以有效避免精度问题的乘法与除法封装

一、使用方法

1、在使用的页面引入

import { JSAdd,JSSub,JSDiv, JSMul } from '../../until/jsOperation'

1、对需要计算的数值

 JSDiv(除数, 被除数)
 
 如:10000/100
 	JSAdd(10000, 100)
 	JSSub(10000, 100)
 	 JSMul(10000, 100)
 	JSDiv(10000, 100)
 	JSDiv(bargainAmountMin, 100)
 	
JSMul()的用法亦如此

二、方法
1、加法

export function JSAdd (a, b) {
  if (!a || !b) {
    return a + b
  }
  let c, d
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  const h = Math.pow(10, Math.max(c, d))
  return (JSMul(a, h) + JSMul(b, h)) / h
}

2、减法

export function JSSub (a, b) {
  if (!a || !b) {
    return a - b
  }
  let c, d
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  const h = Math.pow(10, Math.max(c, d))
  return (JSMul(a, h) - JSMul(b, h)) / h
}

3、乘法

export function JSMul (a, b) {
  if (!a || !b) {
    return 0
  }
  let c = 0
  const d = a.toString()
  const e = b.toString()
  try {
    if (d.split('.')[1]) {
      c += d.split('.')[1].length
    }
  } catch (f) {
    console.log(f)
  }
  try {
    if (e.split('.')[1]) {
      c += e.split('.')[1].length
    }
  } catch (f) {
    console.log(f)
  }
  const result =
      (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
  return result
}

4、除法

export function JSDiv (a, b) {
  if (!a || !b) {
    return 0
  }
  let e = 0
  let f = 0
  try {
    if (a.toString().split('.')[1]) {
      e = a.toString().split('.')[1].length
    }
  } catch (g) {
    console.log(g)
  }
  try {
    if (b.toString().split('.')[1]) {
      f = b.toString().split('.')[1].length
    }
  } catch (g) {
    console.log(g)
  }
  const result = JSMul(
    Number(a.toString().replace('.', '')) /
        Number(b.toString().replace('.', '')),
    Math.pow(10, f - e)
  )
  return result
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值