calc.js 1.16 KB
import { Decimal } from './lib/decimal.min'

export default {
  formatNumber(value) {
    return value ? Number(value) : 0
  },
  // 加
  add(x, y) {
    if (!x) {
      x = 0
    }
    if (!y) {
      y = 0
    }
    const xx = new Decimal(this.formatNumber(x))
    const yy = new Decimal(this.formatNumber(y))
    return xx.plus(yy).toNumber()
  },

  // 减
  reduce(x, y) {
    if (!x) {
      x = 0
    }
    if (!y) {
      y = 0
    }
    const a = this.formatNumber(x)
    const b = this.formatNumber(y)
    const xx = new Decimal(a)
    const yy = new Decimal(b)
    const value = xx.minus(yy).toNumber()
    if (a < b && value > 0) {
      return -value
    }
    return value
  },

  // 乘
  ride(x, y) {
    if (!x) {
      x = 0
    }
    if (!y) {
      y = 0
    }
    const xx = new Decimal(this.formatNumber(x))
    const yy = new Decimal(this.formatNumber(y))
    return xx.mul(yy).toNumber()
  },

  // 除
  except(x, y) {
    if (!x) {
      x = 0
      return 0
    }
    if (!y) {
      y = 0
      return 0
    }
    const xx = new Decimal(this.formatNumber(x))
    const yy = new Decimal(this.formatNumber(y))
    return xx.div(yy).toNumber().toFixed(4)
  }
}