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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | /** * Convert to Chinese amount * * @param amount * the amount * @return the string */ public static String convertToChineseAmt(Long amount) { String num[] = { "零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖" }; String xx[] = { "拾", "佰", "仟" }; String yy[] = { "萬", "億", "兆", "京" }; String chineseAmt = ""; int i; int temp; boolean first = true; boolean zero = false; for (i = 0; (int) (amount / (long) Math.pow(10, i)) != 0; i++) { ;// 計算位數i } if (i == 0) { return num[0]; } for (int k = (i - 1) / 4; k >= 0; k--) { temp = (int) ((amount / (long) Math.pow(10, 4 * k)) % (int) Math.pow(10, 4)); if (temp == 0) { zero = true; continue; } for (int x = 3; x >= 0; x--) { if (first) { x = (i - 1) % 4; first = false; } if (temp / (int) Math.pow(10, x) % 10 == 0) { zero = true; } else { if (zero) { chineseAmt += num[0]; zero = false; } chineseAmt += num[temp / (int) Math.pow(10, x) % 10]; if (x > 0) { chineseAmt += xx[x - 1]; } } } if (k > 0) { chineseAmt = chineseAmt + yy[k - 1]; } } return chineseAmt; } |
Test
We inputted three amount into this method to do conversion
1 2 3 4 5 | public static void main(String args[]) { System.out.println(ReportUtils.convertToChineseAmt(2500L)); System.out.println(ReportUtils.convertToChineseAmt(50100L)); System.out.println(ReportUtils.convertToChineseAmt(325250L)); } |
The result is as bellows:
1 2 3 | 貳仟伍佰 伍萬零壹佰 參拾貳萬伍仟貳佰伍拾 |
No comments:
Post a Comment