如何在JavaScript中将数字转换为英文文本(支持大数自动化转换)
整数转英文拼写实现方案
核心思路
不用Switch语句硬写所有数字的映射,而是通过分段处理(个/十/百位、千位、百万位等)结合基础数字映射表来实现,能覆盖任意大的整数转换。
步骤拆解
- 定义基础映射表
先把0-19、整十数(20、30…90)、以及量级单位(千、百万、十亿)提前定义,这是转换的核心基础:
# 以Python为例,其他编程语言逻辑完全通用 ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["", "thousand", "million", "billion"]
- 处理三位数以内的数字
写一个辅助函数,专门转换0-999之间的数字,返回对应英文片段:
def convert_less_than_one_thousand(num): if num == 0: return "" result = "" # 处理百位 if num >= 100: result += ones[num // 100] + " hundred" num %= 100 if num != 0: result += " and " # 处理十位和个位 if num >= 20: result += tens[num // 10] num %= 10 if num != 0: result += "-" + ones[num] elif num != 0: result += ones[num] return result.strip()
这里要注意:百位非零且后面还有数字时,需添加and;20以上的十位和个位用连字符连接。
- 分段处理大数字
把数字从右往左按每三位拆分,每段对应一个量级单位(千、百万等),再将各段结果拼接:
def number_to_words(num): if num == 0: return "zero" result = "" scale_index = 0 # 从右往左逐段拆分处理 while num > 0: chunk = num % 1000 if chunk != 0: chunk_str = convert_less_than_one_thousand(chunk) # 拼接当前段的量级单位 if scale_index > 0: chunk_str += " " + scales[scale_index] # 将当前段结果加到总结果的前面 if result: result = chunk_str + " " + result else: result = chunk_str num = num // 1000 scale_index += 1 return result
测试示例
- 输入
1→ 返回one - 输入
20→ 返回twenty - 输入
105→ 返回one hundred and five - 输入
1005→ 返回one thousand and five
注意事项
- 英式英语通常在百位后加
and,美式英语有时会省略,可根据需求调整and的添加逻辑。 - 必须单独处理
0的特殊情况,避免返回空字符串。
内容的提问来源于stack exchange,提问作者Nafiz Iqbal
相关产品推荐
相关产品推荐

