java数字转为人民币大写汉字输出
时间: 2023-09-28 19:13:29 浏览: 177
java实现将数字转换成人民币大写
好的,为您提供一个Java代码示例,可以将数字转换为人民币大写汉字输出:
```java
import java.math.BigDecimal;
public class NumberToChinese {
private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] CN_UPPER_MONETARY_UNIT = {"分", "角", "元", "拾", "百", "千", "万", "亿", "元"};
private static final BigDecimal MAX_VALUE = new BigDecimal("9999999999999.99");
public static String number2CNMonetaryUnit(BigDecimal money) {
if (money == null) {
return "";
}
if (money.compareTo(MAX_VALUE) > 0) {
return "";
}
StringBuilder sb = new StringBuilder();
int index = 0;
boolean isZero = true;
int value;
String s = money.movePointRight(2).setScale(0, 4).toString();
if (s.length() > 1 && s.charAt(s.length() - 1) == '0') {
s = s.substring(0, s.length() - 1);
}
int len = s.length();
if (len > 15) {
return "";
}
for (int i = len - 1; i >= 0; i--) {
value = s.charAt(i) - '0';
if (value < 0 || value > 9) {
return "";
}
if (value != 0) {
isZero = false;
sb.insert(0, CN_UPPER_MONETARY_UNIT[index]);
sb.insert(0, CN_UPPER_NUMBER[value]);
} else {
if (!isZero) {
sb.insert(0, CN_UPPER_NUMBER[value]);
}
if (index == 2 || index == 6) {
sb.insert(0, CN_UPPER_MONETARY_UNIT[index]);
}
isZero = true;
}
index++;
}
if (isZero) {
sb.insert(0, "整");
}
return sb.toString();
}
}
```
使用方法:
```java
BigDecimal money = new BigDecimal("1234567.89");
String cnMoney = NumberToChinese.number2CNMonetaryUnit(money);
System.out.println(cnMoney); // 壹佰贰拾叁万肆仟伍佰陆拾柒元捌角玖分
```
请注意,该代码示例只能处理小于等于9999999999999.99的金额,超出范围会返回空字符串。
阅读全文