欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

告诉你什么是优雅的代码(6)------阿拉伯钱数转换为中文形式

程序员文章站 2022-03-02 21:05:43
...
http://www.iteye.com/topic/766812里谈到
题目: 将正整数的阿拉伯钱数转换为中文形式,如1011→一千零一十一,输出。

作者做得相当啰嗦,也比较低效,正好有缘遇到优雅代码大师区区在下,于是一段优雅代码得以诞生:


public class MoneyTrans {
	
	private static String[] ChinaDigit = {"零","一","二","三","四","五","六","七","八","九"};
	private static String[] UNIT = {"","","十","百","千"};
	private static String[] BIGUNIT = {"","万","亿","兆"};
	private static long MAX = 10000000000000000L - 1;
	private char[] digit;
	public String trans(long n) throws Exception{
		if(n > MAX){
			throw new Exception("数字过大,最多可处理到千兆位");
		}
		StringBuffer buff = new StringBuffer();
		boolean isPrePartZero = false;
		digit = String.valueOf(n).toCharArray();
		int length = digit.length;		
		int pos = (length - 1)/4;
		int headLength = (length - 1)%4 + 1;	
		//  xxxxxxxxxx -->  xx|xxxx|xxxx
		buff.append(partTrans(0,headLength) + BIGUNIT[pos--]);
		for (int i = headLength;i < length ; i = i + 4) {
			String part = partTrans(i , i + 4);
			if(part.length() == 0){
				isPrePartZero = true;
			}else{
				if(isPrePartZero && !part.startsWith(ChinaDigit[0])){
					buff.append(ChinaDigit[0]);
				}
				buff.append(part +  BIGUNIT[pos]) ;
				isPrePartZero = false;
			}
			pos--;
		}
		return buff.toString();
	}
	
	private  String partTrans(int start, int end) {
		StringBuffer buff = new StringBuffer();
		boolean isPreDigitZero = false;
		for (int i = start; i < end; i++) {
			int cur = digit[i] - '0';
			if(cur != 0 ){
				if(isPreDigitZero){
					buff.append(ChinaDigit[0]);
				}
				buff.append(ChinaDigit[cur] + UNIT[end - i]);
				isPreDigitZero = false;
			}
			else {			
				isPreDigitZero = true;
			}			
		}		
		return buff.toString();		
	}

	public static void main(String[] args) throws Exception {		
		MoneyTrans transtor = new MoneyTrans();    
		String money = transtor.trans(9000000000000000L);
		System.out.println(money);
	}

}




结果:
九千兆