直接复制测试即可。
public static void main(String[] args) {// String[] num = convert(12345,false);// for (int i=0;i<num.length;i++) {// System.out.println(num[i]);// }int num= 123;System.out.println(cvt(num));}public static String[] convert(long num, boolean isColloquial) {if (num < 10) {// 10如下直接返回对应汉字return new String[] { CN_CHARS[(int) num] };// ASCII2int}char[] chars = String.valueOf(num).toCharArray();if (chars.length > CN_UNITS.length) {// 超过单位表示范围的返回空return new String[] {};}boolean isLastUnitStep = false;// 记录上次单位进位ArrayList<String> cnchars = new ArrayList<String>(chars.length * 2);// 建立数组,将数字填入单位对应的位置for (int pos = chars.length - 1; pos >= 0; pos--) {// 从低位向高位循环char ch = chars[pos];String cnChar = CN_CHARS[ch - '0'];// ascii2int 汉字int unitPos = chars.length - pos - 1;// 对应的单位坐标String cnUnit = CN_UNITS[unitPos];// 单位boolean isZero = (ch == '0');// 是否为0boolean isZeroLow = (pos + 1 < chars.length && chars[pos + 1] == '0');// 是否低位为0boolean isUnitStep = (unitPos >= UNIT_STEP && (unitPos % UNIT_STEP == 0));// 当前位是否须要单位进位if (isUnitStep && isLastUnitStep) {// 去除相邻的上一个单位进位int size = cnchars.size();cnchars.remove(size - 1);if (!CN_CHARS[0].equals(cnchars.get(size - 2))) {// 补0cnchars.add(CN_CHARS[0]);}}if (isUnitStep || !isZero) {// 单位进位(万、亿),或者非0时加上单位cnchars.add(cnUnit);isLastUnitStep = isUnitStep;}if (isZero && (isZeroLow || isUnitStep)) {// 当前位为0低位为0,或者当前位为0而且为单位进位时进行省略continue;}cnchars.add(cnChar);isLastUnitStep = false;}Collections.reverse(cnchars);// 清除最后一位的0int chSize = cnchars.size();String chEnd = cnchars.get(chSize - 1);if (CN_CHARS[0].equals(chEnd) || CN_UNITS[0].equals(chEnd)) {cnchars.remove(chSize - 1);}// 口语化处理if (isColloquial) {String chFirst = cnchars.get(0);String chSecond = cnchars.get(1);if (chFirst.equals(CN_CHARS[1]) && chSecond.startsWith(CN_UNITS[1])) {// 是否以'一'开头,紧跟'十'cnchars.remove(0);}}return cnchars.toArray(new String[] {});}public static String cvt(long num, boolean isColloquial) {String[] result = convert(num, isColloquial);StringBuffer strs = new StringBuffer(32);for (String str : result) {strs.append(str);}return strs.toString();}/*** 单位*/public static String[] CN_UNITS = new String[] { "个", "十", "百", "千", "万", "十","百", "千", "亿", "十", "百", "千", "万" };/*** 汉字*/public static String[] CN_CHARS = new String[] { "零", "一", "二", "三", "四","五", "六", "七", "八", "九" };public static int UNIT_STEP = 4;/*** 数值转换为中文字符串** @param num* 须要转换的数值* @return*/public static String cvt(long num) {return cvt(num, false);}
结果如下:
