编程实现金额转换

金额转换,阿拉伯数字转换成中国传统形式。  例如: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"));
		
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值