Java 将数字金额转成中文大写
时间: 2023-09-08 10:12:26 浏览: 56
Java 可以通过如下代码将数字金额转成中文大写:
```java
import java.math.BigDecimal;
public class MoneyToChinese {
private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] CN_UPPER_MONETARY_UNIT = {"分", "角", "元", "拾", "佰", "仟", "万", "亿", "兆"};
public static String toChinese(BigDecimal money) {
StringBuilder sb = new StringBuilder();
int signum = money.signum();
if (signum == 0) {
return CN_UPPER_NUMBER[0] + CN_UPPER_MONETARY_UNIT[2];
}
long number = money.movePointRight(2).setScale(0, BigDecimal.ROUND_HALF_UP).abs().longValue();
long scale = number % 100;
int numIndex = 0;
int unitIndex = 0;
boolean isZero = true;
if (scale <= 0) {
unitIndex = 2;
number /= 100;
isZero = false;
}
if (number > 0) {
while (number > 0) {
long d = number % 10;
if (d > 0) {
if (unitIndex == 6 && numIndex == 0) {
sb.insert(0, CN_UPPER_MONETARY_UNIT[unitIndex]);
}
if (unitIndex == 7 && numIndex == 0) {
sb.insert(0, CN_UPPER_MONETARY_UNIT[unitIndex]);
}
sb.insert(0, CN_UPPER_MONETARY_UNIT[unitIndex]);
sb.insert(0, CN_UPPER_NUMBER[(int) d]);
isZero = false;
} else {
if (!isZero) {
sb.insert(0, CN_UPPER_NUMBER[0]);
}
isZero = true;
}
numIndex++;
number /= 10;
if (numIndex == 2 && number > 0) {
sb.insert(0, CN_UPPER_MONETARY_UNIT[unitIndex]);
isZero = true;
}
unitIndex++;
}
}
if (isZero) {
sb.insert(0, CN_UPPER_NUMBER[0]);
}
sb.insert(0, CN_UPPER_MONETARY_UNIT[2]);
return sb.toString();
}
}
```
使用方法如下:
```java
BigDecimal money = new BigDecimal("12345.67");
System.out.println(MoneyToChinese.toChinese(money)); // 壹万贰仟叁佰肆拾伍元陆角柒分
```