在 Java 中,怎样将数字转换为单词
在 Java 中,将数字转换为单词可以通过自定义方法实现。以下是实现数字转换为单词的完整代码:
示例代码
import java.util.HashMap;
import java.util.Map;
public class NumberToWords {
// 数字到单词的映射
private static final String[] LESS_THAN_TWENTY = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
private static final String[] TENS = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};
private static final String[] THOUSANDS = {
"", "Thousand", "Million", "Billion"
};
// 主方法
public static String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
StringBuilder result = new StringBuilder();
int thousandIndex = 0;
while (num > 0) {
if (num % 1000 != 0) {
result.insert(0, helper(num % 1000) + THOUSANDS[thousandIndex] + " ");
}
num /= 1000;
thousandIndex++;
}
return result.toString().trim();
}
// 处理 0-999 的数字
private static String helper(int num) {
if (num == 0) {
return "";
} else if (num < 20) {
return LESS_THAN_TWENTY[num] + " ";
} else if (num < 100) {
return TENS[num / 10] + " " + helper(num % 10);
} else {
return LESS_THAN_TWENTY[num / 100] + " Hundred " + helper(num % 100);
}
}
// 测试方法
public static void main(String[] args) {
int num = 1234567;
System.out.println("Number: " + num);
System.out.println("In Words: " + numberToWords(num));
}
}
输出示例
对于输入数字 1234567,输出为:
Number: 1234567
In Words: One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
工作原理
- 拆分数字:
将数字分为千位组(如百万、千、单位)分别处理。 - 小范围映射:
使用数组映射处理 0-19 和整十数(20、30 等)。 - 递归:
对每个千位组调用递归方法,将 0-999 的数字转换为单词。 - 拼接结果:
使用StringBuilder将每个组的结果依次拼接。
可扩展性
- 支持负数:可以在主方法中添加对负数的判断。
- 本地化:修改
LESS_THAN_TWENTY和TENS数组即可支持其他语言。