前端js中的算数精确运算加,减,乘,除,数组求和函数整理

2018-11-23  本文已影响35人  自己对了世界就对了

乘法

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

加法

const add = function(a, b) {
  let c = 0
  let d = 0
  let e = 0
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  e = Math.pow(10, Math.max(c, d))
  return (mul(a, e) + mul(b, e)) / e
}

减法

const sub = function(a, b) {
  let c = 0
  let d = 0
  let e = 0
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  e = Math.pow(10, Math.max(c, d))
  return (mul(a, e) - mul(b, e)) / e
}

除法

const div = function(a, b) {
  let c = 0
  let d = 0
  let e = 0
  let f = 0
  try {
    e = a.toString().split('.')[1].length
  } catch (g) { console.log() }
  try {
    f = b.toString().split('.')[1].length
  } catch (g) { console.log() }
  c = Number(a.toString().replace('.', ''))
  d = Number(b.toString().replace('.', ''))
  return mul(c / d, Math.pow(10, f - e))
}

注:由于算数运算中的加,减,除都是以乘法运算为基础进行的数学运算,所以在用到除乘法外的其他数学运算的时候,乘法必须给带上

数组求和

// 方法1
const sum = function(arr) {
  var len = arr.length
  if (len === 0) {
    return 0
  } else if (len === 1) {
    return arr[0]
  } else {
    return arr[0] + sum(arr.slice(1))
  }
}
// 方法2
const sum = function(arr){
  arr.reduce((p, v, i , a) => {
    return p + v
})
上一篇下一篇

猜你喜欢

热点阅读