其他分享
首页 > 其他分享> > js运算及判断无限循环数进行保留小数位

js运算及判断无限循环数进行保留小数位

作者:互联网

// 判断是否无限循环小数
export function f (n) {
  if (n === 1) return false
  else if (n % 2 === 0) {
    return f(n / 2)
  } else if (n % 5 === 0) {
    return f(n / 5)
  } else return true
}

// 除法函数
export function accDiv (arg1, arg2) {
  let t1, t2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {
    t1 = 0
  }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {
    t2 = 0
  }
  const r1 = Number(arg1.toString().replace('.', ''))
  const r2 = Number(arg2.toString().replace('.', ''))
  const n = (t1 >= t2) ? t1 : t2
  let result = r1 / r2
  if (f(r2)) {
    result = result.toFixed(n > 3 ? n : 3)
  }
  return result * Math.pow(10, t2 - t1)
}

// 乘法函数
export function accMul (arg1, arg2) {
  let m = 0
  const s1 = arg1.toString()
  const s2 = arg2.toString()
  m += s1.split('.')[1] ? s1.split('.')[1].length : 0
  m += s2.split('.')[1] ? s2.split('.')[1].length : 0
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

// 加法函数
export function accAdd (arg1, arg2) {
  let r1, r2
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  const m = Math.pow(10, Math.max(r1, r2))
  return (arg1 * m + arg2 * m) / m
}

// 减法函数
export function Subtr (arg1, arg2) {
  let r1, r2
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  const m = Math.pow(10, Math.max(r1, r2))
  const n = (r1 >= r2) ? r1 : r2
  return Number(((arg1 * m - arg2 * m) / m).toFixed(n))
}

  

标签:r1,r2,arg1,arg2,js,toString,split,小数位,运算
来源: https://www.cnblogs.com/liangtang/p/15938780.html