JS 较大金额格式化

43 篇文章 2 订阅

一、增加单位

addAmountUnit(123456789) => 1.23亿

/**
 * @param integer {number}
 * @returns {number}
 */
export function getDigit(integer) {
  let digit = -1
  while (integer >= 1) {
    digit++
    integer = integer / 10
  }
  return digit
}

/**
 * @param integer {number}
 * @param number {number}
 * @param multiple {number}
 * @param decimal {number}
 * @returns {string|number}
 */
export function addWan(integer, number, multiple, decimal) {
  const digit = getDigit(integer)

  if (digit > 3) {
    let remainder = digit % 8
    if (remainder >= 5) {
      remainder = 4
    }
    return (Math.round(number / Math.pow(10, remainder + multiple - decimal)) / Math.pow(10, decimal) + '万')
  } else {
    return (Math.round(number / Math.pow(10, multiple - decimal)) / Math.pow(10, decimal))
  }
}

/**
 * 金额格式化
 * @param num {number} 金额
 * @param decimal {number} 保留几位小数
 * @returns {string|number|string|*}
 * @description addAmountUnit(123456789) => 1.23亿
 */
export function addAmountUnit(num, decimal = 2) {
  const integer = Math.floor(num)
  const digit = getDigit(integer)
  const unit = []

  if (digit > 3) {
    const multiple = Math.floor(digit / 8)
    if (multiple >= 1) {
      const tmp = Math.round(integer / Math.pow(10, 8 * multiple))

      unit.push(addWan(tmp, num, 8 * multiple, decimal))

      for (let i = 0; i < multiple; i++) {
        unit.push('亿')
      }
      return unit.join('')
    } else {
      return addWan(integer, num, 0, decimal)
    }
  } else {
    return num
  }
}

 二、增加前缀

addCurrency(10000) => ¥10,000.00

/**
 * 金额
 * @param num {number} 金额
 * @param decimal {number} 小数
 * @param cur {string} 前缀
 * @returns {string}
 * @description addCurrency(10000) => ¥10,000.00
 */
export function addCurrency(num, decimal = 2, cur = '¥') {
  num = parseFloat(num)
  if (!isFinite(num) || (!num && num !== 0)) return ''
  const stringed = Math.abs(num).toFixed(decimal)
  const _int = decimal ? stringed.slice(0, -1 - decimal) : stringed
  const i = _int.length % 3
  const head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''
  const _float = decimal ? stringed.slice(-1 - decimal) : ''
  const sign = num < 0 ? '-' : ''
  return (sign + cur + head + _int.slice(i).replace(/(\d{3})(?=\d)/g, '$1,') + _float)
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱宇阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值