Skip to content

@utilslib/core/numberToChinese


将数字转换为中文数字。


numberToChinese

函数签名

typescript
function numberToChinese(value: string | number): string

描述

将数字转换为中文数字。

参数

参数名类型可选默认值描述
valuestring | number--

返回值

string

点击查看源码
js
/**
 * 将数字转换为中文数字。
 *
 * @param {string | number} value - 要转换的数字。
 * @returns {string} 转换后的中文数字。
 */
export function numberToChinese(value) {
  const numberValue = typeof value === "number" ? value.toString() : value;
  const chineseDigits = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
  ];
  const chineseUnits = ["", "十", "百", "千", "万", "亿"];
  const numArray = Array.from(numberValue).reverse();
  const chineseArray = numArray.map((num, index) => {
    const digit = parseInt(num);
    const digitChinese = chineseDigits[digit];
    if (digit === 0) {
      // 如果当前数字为零,则不处理
      return "";
    }
    const unit = index % 4;
    const unitChinese = chineseUnits[unit];
    const isUnitFirst = index === 0 || (index > 0 && digit !== 1 && unit === 0);
    return isUnitFirst ? digitChinese + unitChinese : digitChinese;
  });
  return chineseArray.reverse().join("");
}
ts
/**
 * 将数字转换为中文数字。
 *
 * @param {string | number} value - 要转换的数字。
 * @returns {string} 转换后的中文数字。
 */
export function numberToChinese(value: string | number): string {
  const numberValue = typeof value === "number" ? value.toString() : value;
  const chineseDigits = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
  ];
  const chineseUnits = ["", "十", "百", "千", "万", "亿"];

  const numArray = Array.from(numberValue).reverse();
  const chineseArray = numArray.map((num, index) => {
    const digit = parseInt(num);
    const digitChinese = chineseDigits[digit];

    if (digit === 0) {
      // 如果当前数字为零,则不处理
      return "";
    }

    const unit = index % 4;
    const unitChinese = chineseUnits[unit];
    const isUnitFirst = index === 0 || (index > 0 && digit !== 1 && unit === 0);

    return isUnitFirst ? digitChinese + unitChinese : digitChinese;
  });

  return chineseArray.reverse().join("");
}

如有错误,请提交issue :::