java金额大写转数字
时间: 2023-09-08 18:12:55 浏览: 107
java金额转大写
以下是Java实现大写金额转数字的示例代码:
```java
public class AmountUtil {
private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
private static final String[] CN_UPPER_MONETRAY_UNIT = {"分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
private static final BigDecimal MAX_VALUE = new BigDecimal("9999999999999.99");
/**
* 将大写金额转换为数字形式
*
* @param amount 大写金额
* @return 数字形式
*/
public static BigDecimal convertToNumber(String amount) {
if (!amount.matches("^[壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分]*$")) {
throw new IllegalArgumentException("不是有效的大写金额格式");
}
StringBuilder sb = new StringBuilder(amount);
// 处理万、亿
int index = sb.indexOf("亿");
if (index > -1) {
String temp = sb.substring(0, index);
BigDecimal num = new BigDecimal(convertToNumber(temp).toString());
sb.delete(0, index + 1);
sb.insert(0, " ");
BigDecimal value = new BigDecimal(convertToNumber(sb.toString().trim()).toString());
return num.multiply(new BigDecimal("100000000")).add(value);
}
index = sb.indexOf("万");
if (index > -1) {
String temp = sb.substring(0, index);
BigDecimal num = new BigDecimal(convertToNumber(temp).toString());
sb.delete(0, index + 1);
sb.insert(0, " ");
BigDecimal value = new BigDecimal(convertToNumber(sb.toString().trim()).toString());
return num.multiply(new BigDecimal("10000")).add(value);
}
// 处理元、角、分
BigDecimal result = new BigDecimal("0");
int numIndex = 0;
int unitIndex = 0;
boolean getZero = false;
while (numIndex < amount.length()) {
char c = amount.charAt(numIndex);
if (c >= '壹' && c <= '玖') {
int num = c - '壹' + 1;
if (unitIndex == 2) {
result = result.add(new BigDecimal(num));
} else if (unitIndex == 6) {
result = result.add(new BigDecimal(num).multiply(new BigDecimal("10000")));
} else if (unitIndex == 10) {
result = result.add(new BigDecimal(num).multiply(new BigDecimal("100000000")));
} else {
result = result.add(new BigDecimal(num).multiply(new BigDecimal(Math.pow(10, 3 - unitIndex))));
}
getZero = false;
} else if (c == '零') {
getZero = true;
} else if (CN_UPPER_MONETRAY_UNIT[unitIndex].equals(String.valueOf(c))) {
getZero = false;
} else if (c == '元') {
getZero = false;
} else if (c == '角') {
if (getZero) {
result = result.add(new BigDecimal("0.1"));
}
getZero = false;
} else if (c == '分') {
if (getZero) {
result = result.add(new BigDecimal("0.01"));
}
getZero = false;
}
if (CN_UPPER_MONETRAY_UNIT[unitIndex].equals(String.valueOf(c))) {
++unitIndex;
}
++numIndex;
}
return result;
}
public static void main(String[] args) {
String amount = "壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元零壹分";
System.out.println(convertToNumber(amount)); // 123456789.01
}
}
```
以上代码可以将大写金额转换为数字形式,支持亿、万、元、角、分等单位。注意,该方法只支持中文大写金额格式,不支持阿拉伯数字和英文格式。
阅读全文