Total Pageviews

2013/11/27

How to convert the amount from Arabic numerals to Chinese number (如何將阿拉伯數字金額轉大寫國字)

Requirement
In our payment slip, we need to convert the amount from Arabic numerals to Chinese number. ex. 325250 will be converted to 參拾貳萬伍仟貳佰伍拾.


Solution
Here has a utility method to do conversion.
1:    /**  
2:     * Convert to Chinese amount  
3:     *   
4:     * @param amount  
5:     *      the amount  
6:     * @return the string  
7:     */  
8:    public static String convertToChineseAmt(Long amount) {  
9:      String num[] = { "零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖" };  
10:      String xx[] = { "拾", "佰", "仟" };  
11:      String yy[] = { "萬", "億", "兆", "京" };  
12:      String chineseAmt = "";  
13:      int i;  
14:      int temp;  
15:      boolean first = true;  
16:      boolean zero = false;  
17:      for (i = 0; (int) (amount / (long) Math.pow(10, i)) != 0; i++) {  
18:        ;// 計算位數i  
19:      }  
20:      if (i == 0) {  
21:        return num[0];  
22:      }  
23:      for (int k = (i - 1) / 4; k >= 0; k--) {  
24:        temp = (int) ((amount / (long) Math.pow(10, 4 * k)) % (int) Math.pow(10, 4));  
25:        if (temp == 0) {  
26:          zero = true;  
27:          continue;  
28:        }  
29:        for (int x = 3; x >= 0; x--) {  
30:          if (first) {  
31:            x = (i - 1) % 4;  
32:            first = false;  
33:          }  
34:          if (temp / (int) Math.pow(10, x) % 10 == 0) {  
35:            zero = true;  
36:          } else {  
37:            if (zero) {  
38:              chineseAmt += num[0];  
39:              zero = false;  
40:            }  
41:            chineseAmt += num[temp / (int) Math.pow(10, x) % 10];  
42:            if (x > 0) {  
43:              chineseAmt += xx[x - 1];  
44:            }  
45:          }  
46:        }  
47:        if (k > 0) {  
48:          chineseAmt = chineseAmt + yy[k - 1];  
49:        }  
50:      }  
51:      return chineseAmt;  
52:    }  

Test
We inputted three amount into this method to do conversion
1:    public static void main(String args[]) {  
2:      System.out.println(ReportUtils.convertToChineseAmt(2500L));  
3:      System.out.println(ReportUtils.convertToChineseAmt(50100L));  
4:      System.out.println(ReportUtils.convertToChineseAmt(325250L));  
5:    }  


The result is as bellows:
1:  貳仟伍佰  
2:  伍萬零壹佰  
3:  參拾貳萬伍仟貳佰伍拾  

No comments: