首页前端工具函数价格转换工具函数

价格转换工具函数

分类前端工具函数时间2025-07-18 17:38:47发布RustStream浏览38
摘要:使用方法 parsePrice('19703000' // 19,703,000 parsePrice('19703000', true // 壹仟玖佰柒拾万叁仟 代码实现 // 价格格式化 export function parsePrice(price, toChinese = false { if (price == null || price === '' || isNaN(price retur<!--autointro-->...

使用方法

parsePrice('19703000')   // 19,703,000
parsePrice('19703000', true)   // 壹仟玖佰柒拾万叁仟

代码实现

// 价格格式化
export function parsePrice(price, toChinese = false) {
  if (price == null || price === '' || isNaN(price)) return '';
  if (!toChinese) {
    return Number(price).toLocaleString('en-US');
  }

  // 中文大写数字
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const cnIntRadice = ['', '拾', '佰', '仟'];
  const cnIntUnits = ['', '万', '亿'];
  let num = Number(price);
  if (num === 0) return cnNums[0];

  let str = '';
  let unitPos = 0;
  let needZero = false;

  function sectionToChinese(section) {
    let strIns = '', chnStr = '';
    let unitPos = 0;
    let zero = true;
    while (section > 0) {
      let v = section % 10;
      if (v === 0) {
        if (!zero) {
          zero = true;
          chnStr = cnNums[0] + chnStr;
        }
      } else {
        zero = false;
        strIns = cnNums[v] + cnIntRadice[unitPos];
        chnStr = strIns + chnStr;
      }
      unitPos++;
      section = Math.floor(section / 10);
    }
    return chnStr;
  }

  let integerNum = Math.floor(num);
  let unitCount = 0;
  while (integerNum > 0 && unitCount < cnIntUnits.length) {
    let section = integerNum % 10000;
    if (section !== 0) {
      let sectionChinese = sectionToChinese(section);
      if (needZero) {
        str = cnNums[0] + str;
      }
      str = sectionChinese + cnIntUnits[unitCount] + str;
      needZero = section < 1000 && section > 0;
    } else {
      needZero = true;
    }
    integerNum = Math.floor(integerNum / 10000);
    unitCount++;
  }

  // 去除多余的零
  str = str.replace(/零+/g, '零');
  str = str.replace(/零(万|亿)/g, '$1');
  str = str.replace(/亿万/, '亿');
  str = str.replace(/零+$/, '');

  return str;
}

本文链接:https://blog.smallhao.fun/?id=36 转载需授权!

分享到:

Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

vue 常见问题 汇总 根据类型获取对应的时间段(1-本月,2-上个月,3-近三个月,4-近一年)

游客 回复需填写必要信息
召唤伊斯特瓦尔