1. 程式人生 > >Java演算法程式設計

Java演算法程式設計

輸入金額,然後轉換成中文大寫的金額:

/**
 * 輸入的金額轉換成中文大寫,16位數字精確到小數點後2位數
 *
 */
public class MoneyToCNFormat {
    private static final String[] CN_NUMBERS = { "零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖" };
    private static final String[] CN_MONETETARY_UNIT = { "分", "角", "元", "拾", "佰", "仟", 
    "萬", "拾", "佰"
, "仟", "億", "拾", "佰", "仟", "兆", "拾", "佰", "仟" }; private static final String CN_FULL = "整"; private static final String CN_NEGATIVE = "負"; private static final String CN_ZERO = "零角零分"; private static final long MAX_NUMBER = 10000000000000000l;//最大16位整數 private static final String INVALID_AMOUNT = "金額超出最大金額千兆億(16位整數)"
; public static void main(String[] args) { double amountTest = 987654321654321.12d; System.out.println("金額["+amountTest+"]=" + formatToCN(amountTest)); } public static String formatToCN(double amount) { if(Math.abs(amount) >= MAX_NUMBER) return INVALID_AMOUNT; StringBuilder result = new
StringBuilder(); long value = Math.abs(Math.round(amount*100)); int i = 0; while (true) { int temp = (int) (value % 10); result.insert(0, CN_MONETETARY_UNIT[i]); result.insert(0, CN_NUMBERS[temp]); value = value / 10; if (value < 1) break; i++; } //"零角零分" 轉換成 "整" int index = result.indexOf(CN_ZERO); if(index > -1) { result.replace(index, index + 4, CN_FULL); } //負數 if(amount < 0) { result.insert(0, CN_NEGATIVE); } return result.toString(); } }