首页 > 代码库 > 千亿级别数字的人民币读法

千亿级别数字的人民币读法

</pre><pre name="code" class="java">package com.sungeo;
/**
 * 人民币的读法是四位一节;  x仟x百x拾 x  (亿)     x仟x百x拾 x  (万) x仟x百x拾 x 
 * @author Administrator
 */
public class NumToRmb {
	private String[] hanArr=new String[]{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
	private String[] unitArr=new String[]{"拾","百","仟"};
	private String[] wyArr=new String[]{"万","亿"};
	private static String[]  xiaoArr=new String[]{"分","角","圆"};

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		NumToRmb toRMB=new NumToRmb();
		String[] arr=toRMB.divideDouble(12001234.12);//输入数字,变成保留两位小数的人民币读法,支持千亿级别的人民币读法
		int len=checkLength(arr[0]);
		String readHan="";
		if(len<=4){
			readHan=toRMB.readZheng4(arr[0]);
		}else if(len<=8){
			readHan=toRMB.readZheng8(arr[0]);
		}else if(len<=12){
			readHan=toRMB.readZheng12(arr[0]);
		}else {
			System.out.println("只支持千亿级读法!");
		}
		
		System.out.println(readHan+(readHan==""?"":xiaoArr[2])+toRMB.readXiao(arr[1]));
	}
	
	private static int checkLength(String str){
		return str.length();
	}
	/**
	 *  长度小于等于12的整数读法
	 */
	private String readZheng12(String numStr){
		String result="";
		String last8Str=numStr.substring(numStr.length()-8);
		String result8=readZheng8(last8Str);
		String first=numStr.substring(0, numStr.length()-8);
		String firstStr=readZheng4(first);
		result=firstStr+wyArr[1]+result8;
		return result;
	}	
	/**
	 * 长度小于等于8的整数读法
	 * @param numStr
	 * @return
	 */
	private String readZheng8(String numStr){
		String result="";
		String last4Str=numStr.substring(numStr.length()-4);
		String result4=readZheng4(last4Str);
		String first=numStr.substring(0, numStr.length()-4);
		String firstStr=readZheng4(first);
		result=firstStr+wyArr[0]+result4;
		return result;
	}
	
	
	/**
	 *长度小于等于4的整数的读法
	 */
	private String readZheng4(String numStr){
		String result="";
		for(int i=0;i<numStr.length();i++){
			int num=numStr.charAt(i)-48;//‘4’->4;
			if(num!=0&&i!=numStr.length()-1){
				result+=hanArr[num]+unitArr[numStr.length()-i-2];
			}else if(num==0){ //中间为0的不读取
			}else {
				result+=hanArr[num];
			}
		}
		return result;
	}
	
	/**
	 * 小数的读法
	 */
	private String readXiao(String xiaoStr){
		String result="";
		for(int i=0;i<xiaoStr.length();i++){
			int num=xiaoStr.charAt(i)-48;//‘4’->4;
			if(num!=0 ){
				result+=hanArr[num]+xiaoArr[xiaoArr.length-i-2];
			}
		}
		return result;
	}

	/**
	 * 将一个double数分割成小数和整数两部分;   3.14d -> {"3","14"}
	 * @param d  要分割的double 数
	 * @return   整数和小数形成的字符串数组 
	 */
	private String[] divideDouble(double d){
		if(d<=0){
			System.out.println("请输入有效金额!");
		}
		String zheng=(long)d+"";
		String xiao=(long)Math.round((d%1*100))+"";
		return new String[]{zheng,xiao};
	}

}