package com.ruoyi.stock.word;
|
|
import java.math.BigDecimal;
|
|
/**
|
* 金额数字转大写工具类
|
*/
|
public class ChineseNumberUtil {
|
|
private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
|
private static final String[] CN_UPPER_UNIT = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
|
private static final String CN_DOLLAR = "";
|
private static final String CN_TEN_CENT = "点";
|
private static final String CN_CENT = "";
|
private static final String CN_INTEGER = "整";
|
|
/**
|
* 将数字转换为大写金额
|
* @param number 数字(单位:吨)
|
* @return 大写金额字符串
|
*/
|
public static String numberToChinese(BigDecimal number) {
|
if (number == null) {
|
return "零";
|
}
|
|
// 处理负数
|
boolean isNegative = false;
|
if (number.compareTo(BigDecimal.ZERO) < 0) {
|
isNegative = true;
|
number = number.abs();
|
}
|
|
StringBuilder result = new StringBuilder();
|
|
// 分离整数和小数部分
|
String[] parts = number.toString().split("\\.");
|
String integerPart = parts[0];
|
String decimalPart = parts.length > 1 ? parts[1] : "";
|
|
// 转换整数部分
|
if (!"0".equals(integerPart)) {
|
result.append(convertIntegerPart(integerPart));
|
} else {
|
result.append("零");
|
}
|
|
// 转换小数部分
|
if (decimalPart.length() > 0 && !"00".equals(decimalPart) && !"0".equals(decimalPart)) {
|
result.append(CN_TEN_CENT);
|
char[] decimals = decimalPart.toCharArray();
|
for (int i = 0; i < decimals.length; i++) {
|
if (decimals[i] != '0') {
|
result.append(CN_UPPER_NUMBER[Integer.parseInt(String.valueOf(decimals[i]))]);
|
} else {
|
if (i < decimals.length - 1 && decimals[i + 1] != '0') {
|
result.append(CN_UPPER_NUMBER[0]);
|
}
|
}
|
}
|
}
|
|
return isNegative ? "负" + result.toString() : result.toString();
|
}
|
|
/**
|
* 转换整数部分
|
*/
|
private static String convertIntegerPart(String integerPart) {
|
StringBuilder result = new StringBuilder();
|
int length = integerPart.length();
|
|
for (int i = 0; i < length; i++) {
|
int digit = Integer.parseInt(String.valueOf(integerPart.charAt(i)));
|
int unitIndex = length - i - 1;
|
|
if (digit != 0) {
|
result.append(CN_UPPER_NUMBER[digit]).append(CN_UPPER_UNIT[unitIndex]);
|
} else {
|
// 处理连续的零
|
if (i > 0 && integerPart.charAt(i - 1) != '0') {
|
result.append(CN_UPPER_NUMBER[0]);
|
}
|
// 处理万位和亿位
|
if (unitIndex == 4 || unitIndex == 8) {
|
if (result.length() > 0 && !result.toString().endsWith(CN_UPPER_NUMBER[0])) {
|
result.append(CN_UPPER_UNIT[unitIndex]);
|
}
|
}
|
}
|
}
|
|
String resultStr = result.toString();
|
// 去除末尾的零
|
while (resultStr.endsWith(CN_UPPER_NUMBER[0])) {
|
resultStr = resultStr.substring(0, resultStr.length() - 1);
|
}
|
|
return resultStr;
|
}
|
}
|