阿拉伯數字「0」有「零」和「〇」兩種漢字書寫形式。一個數字用做計量時,其中「0」的漢字書寫形式爲「零」,用做編號時,「0」的漢字書寫形式爲「〇」。java
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { private static final String[] CN_NUMBER = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; private static final String[] CN_UNIT = { "", "十", "百", "千" }; /** * 格式化:數字轉漢字 * 未完待續.. * @param str * @return */ public String formatMethod(String str) { str = str.replace(" ", ""); //刪除空格 Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$"); //非負數 Matcher flag = pattern.matcher(str); if (!flag.matches()) { //System.out.println("格式不正確!"); return null; } String p_int = str.split("\\.")[0]; //整數部分 String p_dec = str.indexOf(".") == -1 ? "" : str.split("\\.")[1]; //小數部分 String[] intArr = split(p_int); //分隔,每4位爲一組 return null; } /** * 格式化4位整數 * @param str * @return */ public String formatInt(String str) { StringBuilder sb = new StringBuilder(); boolean isZero = false; for (int i = 0; i < str.length(); i++) { //int n = Integer.valueOf(str.charAt(i) + ""); int n = str.charAt(i) - 48; //0-9的ASCII碼爲48-57 if (n == 0) { isZero = true; } else { if (isZero) { sb.append(CN_NUMBER[str.charAt(i - 1) - 48]); } sb.append(CN_NUMBER[n]); sb.append(CN_UNIT[str.length() - 1 - i]); isZero = false; } } return sb.toString(); } /** * 分隔,每4位爲一組。例:輸入0123456,輸出[0012, 3456] * @param num * @return */ public String[] split(String num) { int remainder = num.length() % 4; //取餘 if (remainder != 0) { String pre = num.substring(0, remainder); String suf = num.substring(remainder); num = String.format("%04d", Integer.valueOf(pre)) + suf; } String[] arr = new String[num.length() / 4]; int j = 0; for (int i = 0; i < num.length(); i += 4) { arr[j++] = num.substring(i, i + 4); } return arr; } /** * 例:輸入2018,輸出二〇一八 * @param str * @return */ public String toYear(String str) { StringBuilder sb = new StringBuilder(str); for (int i = 0; i < str.length(); i++) { sb.replace(i, i + 1, CN_NUMBER[str.charAt(i) - 48]); } return sb.toString(); } }