1. 程式人生 > >java將金額轉換為大寫中文

java將金額轉換為大寫中文

public class NumberUtil {
	  private static final String UNIT[] = { "萬", "仟", "佰", "拾", "億", "仟", "佰",  
	            "拾", "萬", "仟", "佰", "拾", "元", "角", "分" };  
	    private static final String NUM[] = { "零", "壹", "貳", "叄", "肆", "伍", "陸",  
	            "柒", "捌", "玖" };  
	    /** 
	     * 將金額小數轉換成中文大寫金額 
	     * @param money 
	     * @return result 
	     */  
	    public static String Test2(double money) {  
	        long money1 = Math.round(money * 100); // 四捨五入到分  
	        if (money1 == 0) return "零元整";  
	        String strMoney = String.valueOf(money1);//將long型別的轉化為字串 
	        int numIndex = 0; // numIndex用於選擇金額數值  
	        int unitIndex = UNIT.length - strMoney.length(); // unitIndex用於選擇金額單位  
	        boolean isZero = false; // 用於判斷當前為是否為零  
	        String result = "";  
	        for (; numIndex < strMoney.length(); numIndex++, unitIndex++){
	            char num = strMoney.charAt(numIndex);  
	            if (num == '0') {  
	                isZero = true;  
	                if (UNIT[unitIndex] == "億" || UNIT[unitIndex] == "萬" || UNIT[unitIndex] == "元") { // 如果當前位是億、萬、元,且數值為零  
	                    result = result + UNIT[unitIndex]; //補單位億、萬、元  
	                    isZero = false;  
	                }   
	            }else {  
	                if (isZero) {  
	                    result = result + "零";  
	                    isZero = false;  
	                }  
	                result = result + NUM[Integer.parseInt(String.valueOf(num))] + UNIT[unitIndex];  
	            }  
	        }  
	        //不是角分結尾就加"整"字  
	        if (!result.endsWith("角")&&!result.endsWith("分")) {  
	            result = result + "整";  
	        }  
	        //例如沒有這行程式碼,數值"400000001101.2",輸出就是"肆千億萬壹千壹佰零壹元貳角"  
	        result = result.replaceAll("億萬", "億");  
	        return result;  
	    }
}