1.背景
1.1.因為項目的需要,需要把阿拉伯金額的錢數轉化為大寫的工具類,下面直接上代碼。
2.Util
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseYuanUtil {
private static final Pattern AMOUNT_PATTERN = Pattern.compile("^(0|[1-9]\\d{0,11})\\.(\\d\\d)$"); // 不考慮分隔符的正确性
private static final char[] RMB_NUMS = "零壹貳叁肆伍陸柒捌玖".toCharArray();
private static final String[] UNITS = { "元", "角", "分", "整" };
private static final String[] U1 = { "", "拾", "佰", "仟" };
private static final String[] U2 = { "", "萬", "億" };
/**
* 将金額(整數部分等于或少于 12 位,小數部分 2 位)轉換為中文大寫形式.
*
* @param amount 金額數字
* @return 中文大寫
* @throws IllegalArgumentException
*/
public static String convert(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 += integer2rmb(integer) + UNITS[0]; // 整數部分
}
if (fraction.equals("00")) {
result += UNITS[3]; // 添加[整]
} else if (fraction.startsWith("0") && integer.equals("0")) {
result += fraction2rmb(fraction).substring(1); // 去掉分前面的[零]
} else {
result += fraction2rmb(fraction); // 小數部分
}
return result;
}
// 将金額小數部分轉換為中文大寫
private static String fraction2rmb(String fraction) {
char jiao = fraction.charAt(0); // 角
char fen = fraction.charAt(1); // 分
return (RMB_NUMS[jiao - '0'] + (jiao > '0' ? UNITS[1] : ""))
+ (fen > '0' ? RMB_NUMS[fen - '0'] + UNITS[2] : "");
}
// 将金額整數部分轉換為中文大寫
private static String integer2rmb(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(U2[j / 4]);
}
}
} else {
if (j % 4 == 0) {
buffer.append(U2[j / 4]); // 插入[萬]或者[億]
}
buffer.append(U1[j % 4]); // 插入[拾]、[佰]或[仟]
buffer.append(RMB_NUMS[n - '0']); // 插入數字
}
}
return buffer.reverse().toString();
}
}
3.工具類使用
public static void main(String[] args) {
System.out.println(ChineseYuanUtil.convert("16,409.02"));
}
4.結果
壹萬陸仟肆佰零玖元零貳分
5.結束
Always keep the faith!!!