Java如何將數(shù)字轉(zhuǎn)為中文大寫(xiě)
在Java中,我們可以使用一些方法將數(shù)字轉(zhuǎn)換為中文大寫(xiě)。下面是一種常見(jiàn)的實(shí)現(xiàn)方式:
`java
public class NumberToChinese {
private static final String[] CN_NUMBERS = {"零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖"};
private static final String[] CN_UNITS = {"", "拾", "佰", "仟", "萬(wàn)", "億"};
public static String toChinese(int number) {
if (number == 0) {
return CN_NUMBERS[0];
}
StringBuilder result = new StringBuilder();
int unitIndex = 0;
while (number > 0) {
int digit = number % 10;
if (digit != 0) {
result.insert(0, CN_UNITS[unitIndex]);
result.insert(0, CN_NUMBERS[digit]);
}
number /= 10;
unitIndex++;
}
return result.toString();
}
public static void main(String[] args) {
int number = 12345;
String chineseNumber = toChinese(number);
System.out.println(chineseNumber); // 輸出:壹萬(wàn)貳仟叁佰肆拾伍
}
`
以上代碼中,我們定義了兩個(gè)數(shù)組 CN_NUMBERS 和 CN_UNITS,分別表示數(shù)字和單位的中文大寫(xiě)。然后,我們使用循環(huán)將數(shù)字逐位轉(zhuǎn)換為中文大寫(xiě),并根據(jù)位數(shù)添加對(duì)應(yīng)的單位。將轉(zhuǎn)換后的結(jié)果返回。
在 main 方法中,我們給定一個(gè)數(shù)字 12345,調(diào)用 toChinese 方法將其轉(zhuǎn)換為中文大寫(xiě),并輸出結(jié)果。
這樣,我們就可以通過(guò)調(diào)用 toChinese 方法將任意數(shù)字轉(zhuǎn)換為中文大寫(xiě)了。