public class numberToChinese {
private static final String[] UNITS = { "一", "二", "三", "四", "五", "六", "七", "八", "九","十"};
private static final String[] UNITSK = {"十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九"};
private static final String[] TEENS = {"一十", "二十", "三十", "四十", "五十", "六十", "七十", "八十", "九十"};
public String numberToChinese(int num) {
if (num<10&&num>0){
return UNITS[num-1];
}
if (num == 0) {
return "零";
}
if (num>=10&&num<=19){
int result=num%10;
return UNITSK[result];
}
StringBuilder result = new StringBuilder();
if (num >= 10000) {
throw new IllegalArgumentException("超出范围(只支持0-9999)");
}
int thousands = num / 1000;
if (thousands > 0) {
if (thousands==2){
result.append("两千");
}else {
result.append(UNITS[thousands-1]).append("千");
}
num %= 1000;
// 处理千位之后的零,如2005应为两千零五,而非两千五百
if (num != 0) {
result.append(num < 100 ? "零" : "");
}
}
int hundreds = num / 100;
if (hundreds > 0) {
if (hundreds==2){
result.append("两百");
}else {
result.append(UNITS[hundreds - 1]).append("百");
}
num %= 100;
}
Boolean flag=false;
if (num >= 10) {
int tensIndex = num / 10 - 1; // 转换为TEENS数组的索引
result.append(TEENS[tensIndex]);
num %= 10;
flag=true;
}
if (num > 0) {
if (flag){
result.append(UNITS[num-1]);
}else {
result.append("零").append(UNITS[num-1]);
}
}
// 处理连续的零和一的情况
String strResult = result.toString();
return strResult.isEmpty() ? "零" : simplifyZeros(strResult);
}
public static void main(String[] args) {
numberToChinese number = new numberToChinese();
System.out.println(number.numberToChinese(1001));
}
public static String simplifyZeros(String number) {
return number.replaceAll("(零)+", "零");
}
}
在(0~9999)范围内将数字转成汉字形式
于 2024-01-04 10:25:33 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)