Java代碼實現數字金額轉換為中文大寫形式


代碼:

package com.example.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MoneyTest {

private static final Pattern AMOUNT_PATTERN = Pattern.compile("^(0|[1-9]\\d{0,11})\\.(\\d\\d)$");
private static final char[] RMB_NUMS = {'零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖'};
private static final String[] UNITS1 = {"元", "角", "分", "整"};
private static final String[] UNITS2 = {"", "拾", "佰", "仟"};
private static final String[] UNITS3 = {"", "萬", "億"};

public static void main(String[] args) {
System.out.println(numberConvertAmount("100500.32"));

}

/**
* 將金額(整數部分等於或少於 12 位,小數部分 2 位)轉換為中文大寫形式.
*
* @param amount 金額數字
* @return 中文大寫
* @throws IllegalArgumentException
*/
public static String numberConvertAmount(String amount) throws IllegalArgumentException {
// 去掉分隔符
amount = amount.replace(",", "");
// 驗證金額正確性
if (amount.equals("0.00")) {
throw new IllegalArgumentException("金額不能為零.");
}
Matcher matcher = AMOUNT_PATTERN.matcher(amount);
if (!matcher.find()) {
throw new IllegalArgumentException("輸入金額有誤.");
}

String integer = matcher.group(1); // 整數部分
String fraction = matcher.group(2); // 小數部分

String result = "";
if (!integer.equals("0")) {
result += integerToRmb(integer) + UNITS1[0]; // 整數部分
}
if (fraction.equals("00")) {
result += UNITS1[3]; // 添加[整]
} else if (fraction.startsWith("0") && integer.equals("0")) {
result += fractionToRmb(fraction).substring(1); // 去掉分前面的[零]
} else {
result += fractionToRmb(fraction); // 小數部分
}

return result;
}

// 將金額小數部分轉換為中文大寫
private static String fractionToRmb(String fraction) {
char jiao = fraction.charAt(0); // 角
char fen = fraction.charAt(1); // 分
return (RMB_NUMS[jiao - '0'] + (jiao > '0' ? UNITS1[1] : ""))
+ (fen > '0' ? RMB_NUMS[fen - '0'] + UNITS1[2] : "");
}

// 將金額整數部分轉換為中文大寫
private static String integerToRmb(String integer) {
StringBuilder buffer = new StringBuilder();
// 從個位數開始轉換
int i, j;
for (i = integer.length() - 1, j = 0; i >= 0; i--, j++) {
char n = integer.charAt(i);
if (n == '0') {
// 當 n 是 0 且 n 的右邊一位不是 0 時,插入[零]
if (i < integer.length() - 1 && integer.charAt(i + 1) != '0') {
buffer.append(RMB_NUMS[0]);
}
// 插入[萬]或者[億]
if (j % 4 == 0) {
if (i > 0 && integer.charAt(i - 1) != '0' || i > 1 && integer.charAt(i - 2) != '0'
|| i > 2 && integer.charAt(i - 3) != '0') {
buffer.append(UNITS3[j / 4]);
}
}
} else {
if (j % 4 == 0) {
buffer.append(UNITS3[j / 4]); // 插入[萬]或者[億]
}
buffer.append(UNITS2[j % 4]); // 插入[拾]、[佰]或[仟]
buffer.append(RMB_NUMS[n - '0']); // 插入數字
}
}
return buffer.reverse().toString();
}
}

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM