Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

阿拉伯数字专汉字 #265

Open
Sunny-117 opened this issue Nov 4, 2022 · 3 comments
Open

阿拉伯数字专汉字 #265

Sunny-117 opened this issue Nov 4, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@ixindong
Copy link

const digits = '零一二三四五六七八九';
const units = ['', '十', '百', '千', '万', '亿'];

const toChinese = (num) => {
if (num === 0) return digits[0];
const nums = String(num).split('').reverse().map(Number);
const result = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
result.push(digits[nums[i]] + units[i]);
} else if (i !== 0 && result[result.length - 1] !== digits[0]) {
result.push(digits[0]);
}
}
return result.reverse().join('');
};

@ixindong
Copy link

该函数接受一个数字作为参数,返回对应的汉字字符串。具体实现中定义了两个字符串常量,一个用于表示阿拉伯数字,一个用于表示单位。然后将数字转换成数组,并从低位到高位遍历,依次将每个数字转换成汉字,并加上对应的单位。在转换过程中,需要特别注意数字 0 的处理,它需要根据前面是否有数字来判断是否需要转换成“零”。

@Liu6625
Copy link

Liu6625 commented Oct 19, 2023

function numToChinese(num){
  const digits = '零一二三四五六七八九';
  const units = ['', '十', '百', '千'];
  const bigUnits = ['', '万', '亿', '万亿'];

  const numStr = num.toString();
  const len = numStr.length;

  let chineseNumber = '';
  for (let unitIndex = len - 1 ; unitIndex >= 0; unitIndex--) {
    const digit = numStr[len - 1 - unitIndex];

    if(digit === '0'){
      if(chineseNumber[chineseNumber.length-1]!==digits[0] && unitIndex !== 0){
        chineseNumber += digits[0];
      }
    }else{
      chineseNumber += digits[digit] + units[unitIndex%4];
    }
    
    if(unitIndex%4 === 0 && unitIndex < 12){
      chineseNumber += bigUnits[Math.floor(unitIndex/4)];
    }
  }

  return chineseNumber;
}
console.log(numToChinese(102345060))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants