金额转换,阿拉伯数字转换成中国传统形式。 例如:101000001010 转换为 壹仟零壹拾億零壹仟零壹拾圆整
package com.heima.question10;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.junit.Test;
/**
* @author Alex Zhuang
*
*/
public class MoneyConvert {
private static final char[] CHINESE_NUM = new char[] { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
private static final char[] CHINESE_MONEY_UNIT = new char[] { '圆', '拾', '佰', '仟' };
private static final String[] CHINESE_MONEY_BIG_UNIT = new String[] { "万", "億" , "万" , "兆" };
@Test
public void test(){
assertEquals("柒圆",convertToChinese("7"));
assertEquals("壹仟零壹拾億壹仟零壹拾圆整",convertToChinese("101000001010"));
assertEquals("壹仟贰佰叁拾肆兆伍仟陆佰柒拾捌万玖仟零壹拾贰億叁仟肆佰伍拾陆万柒仟捌佰玖拾圆整",convertToChinese("12345678901234567890"));
assertEquals("壹仟兆圆整",convertToChinese("10000000000000000000"));
assertEquals("贰万叁仟肆佰玖拾贰億捌仟柒佰叁拾肆万玖仟捌佰叁拾肆圆",convertToChinese("2349287349834"));
}
public static String convertToChinese(String moneyStr){
if(moneyStr.length()<=20){
BigInteger money = new BigInteger(moneyStr);
StringBuilder sb = new StringBuilder();
int unitLevel=0;
int bigUnitLevel=0;
while(money.compareTo(BigInteger.ZERO)>0){
/*将输入金额对10取余操作*/
int i = money.remainder(BigInteger.TEN).intValue();
if(unitLevel==4){
sb.insert(0, CHINESE_MONEY_BIG_UNIT[bigUnitLevel]);
bigUnitLevel++;
unitLevel=0;
}else{
/*当单位对应的数字不为零时才输出该单位*/
if(i!=0){
sb.insert(0, CHINESE_MONEY_UNIT[unitLevel]);
/*判断该数字是否为个位数,如是则在字符数串后加圆*/
}else if(bigUnitLevel==0&&unitLevel==0){
sb.insert(0, CHINESE_MONEY_UNIT[unitLevel]);
/*如果个位数的数字为零,则在最后面加字符'整' */
if(i==0){
sb.append('整');
}
}
}
sb.insert(0, CHINESE_NUM[i]);
money=money.divide(BigInteger.TEN);
unitLevel++;
}
String str = sb.toString();
for(int i=0;i<4;i++){
str=str.replaceAll("零兆", "兆");
str=str.replaceAll("零億", "億");
str=str.replaceAll("零万", "万");
str=str.replaceAll("零圆", "圆");
}
str=str.replace("兆万億", "兆");
str=str.replace("億万", "億");
str=str.replace("兆万", "兆");
return str;
}else{
return "输入金额过大,已达到或超过1万兆,无法转换";
}
}
public static void main(String[] args){
System.out.println("7="+convertToChinese("7"));
System.out.println("101000001010="+convertToChinese("101000001010"));
System.out.println("10000000000000000000="+convertToChinese("10000000000000000000"));
System.out.println("12345678901234567890="+convertToChinese("12345678901234567890"));
System.out.println("2349287349834="+convertToChinese("2349287349834"));
}
}