JAVA编写一个包装类,将基本数据类型int转换为中文大写数字
时间: 2024-06-11 18:08:34 浏览: 128
public class ChineseNumber {
private static final String[] CN_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] CN_UNITS = {"", "拾", "佰", "仟", "万", "亿"};
public static String toChineseNumber(int num) {
if (num == 0) {
return CN_NUMBERS[0];
}
StringBuilder sb = new StringBuilder();
int unitIndex = 0;
boolean zero = true;
while (num > 0) {
int digit = num % 10;
if (digit == 0) {
if (!zero) {
zero = true;
sb.insert(0, CN_NUMBERS[0]);
}
} else {
zero = false;
sb.insert(0, CN_NUMBERS[digit] + CN_UNITS[unitIndex]);
}
unitIndex++;
num /= 10;
}
return sb.toString();
}
}
// Usage
int num = 123456;
String cnNum = ChineseNumber.toChineseNumber(num);
System.out.println(cnNum); // "壹拾贰万叁仟肆佰伍拾陆"
阅读全文