小数、整数转中文大写
1、可转化小数的数字成为大写中文数字

2、代码如下
java
public class NumberToChineseUtils {
private static final String[] CAPITAL_NUMS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] UNITS = {"", "拾", "佰", "仟"};
private static final String[] BIG_UNITS = {"", "万", "亿", "万亿"};
private static final String[] DECIMAL_UNITS = {"角", "分", "厘"};
public static String toChineseUpperCase(double amount) {
if (Math.abs(amount) < 0.0005) return "零元整";
String prefix = amount < 0 ? "负" : "";
String strAmount = String.format("%.3f", Math.abs(amount));
String[] parts = strAmount.split("\\.");
long integerPart = Long.parseLong(parts[0]);
String decimalPart = parts[1];
StringBuilder result = new StringBuilder();
// 1. 处理整数部分
if (integerPart > 0) {
result.append(integerToChinese(integerPart)).append("元");
}
// 2. 处理小数部分
boolean hasDecimal = false;
for (int i = 0; i < decimalPart.length(); i++) {
int digit = decimalPart.charAt(i) - '0';
if (digit > 0) {
// 如果整数部分有值,且当前位(如分)前有0(如角为0),补一个"零"
if (integerPart > 0 && !hasDecimal && i > 0 && (result.length() > 0 && !result.toString().endsWith("零"))) {
// 仅在"元"之后补零,例如:壹元零贰分
result.append("零");
}
result.append(CAPITAL_NUMS[digit]).append(DECIMAL_UNITS[i]);
hasDecimal = true;
}
}
// 3. 最终修整
String finalResult = result.toString()
.replaceAll("零+", "零")
.replaceAll("零$", "");
// 处理结尾:如果没有小数,加"整";如果没有内容,说明是0
if (!hasDecimal) {
finalResult += "整";
}
// 核心修复:确保开头不会出现"零"字,除非金额本身就是0
finalResult = prefix + finalResult;
if (finalResult.startsWith("零") && finalResult.length() > 1) {
finalResult = finalResult.substring(1);
}
return finalResult.isEmpty() ? "零元整" : finalResult;
}
private static String integerToChinese(long num) {
StringBuilder sb = new StringBuilder();
int unitIndex = 0;
while (num > 0) {
int section = (int) (num % 10000);
if (section != 0) {
sb.insert(0, sectionToChinese(section) + BIG_UNITS[unitIndex]);
} else if (sb.length() > 0 && !sb.toString().startsWith("零")) {
sb.insert(0, "零");
}
num /= 10000;
unitIndex++;
}
return sb.toString().replaceAll("零+", "零").replaceAll("零$", "");
}
private static String sectionToChinese(int section) {
StringBuilder sb = new StringBuilder();
boolean zeroFlag = true;
for (int i = 0; i < 4; i++) {
int digit = section % 10;
if (digit == 0) {
if (!zeroFlag) {
zeroFlag = true;
sb.insert(0, CAPITAL_NUMS[0]);
}
} else {
zeroFlag = false;
sb.insert(0, CAPITAL_NUMS[digit] + UNITS[i]);
}
section /= 10;
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("12.56 -> " + toChineseUpperCase(12.56)); // 壹拾贰元伍角陆分
System.out.println("0.56 -> " + toChineseUpperCase(0.56)); // 伍角陆分
System.out.println("1005.02 -> " + toChineseUpperCase(1005.02)); // 壹仟零伍元零贰分
System.out.println("0.003 -> " + toChineseUpperCase(0.003)); // 叁厘
System.out.println("10.00 -> " + toChineseUpperCase(10.00)); // 壹拾元整
}