本文提供八位数以内的转换,八位数以上可以自行修改。
例如: 10 -> 十; 1002 -> 一千零二; 100021 ->十万零二十一; 1111111->一百一十一万一千一百一十一;
package com.huang.number;
/**
* Created by HuangGuojun on 2018/11/10.
*/
public class NumberToBeChinese {
public static void main(String[] args) {
// 测试用例
System.out.println(toChinese("123"));
System.out.println(toChinese("1230000"));
System.out.println(toChinese("123111"));
System.out.println(toChinese("1231"));
System.out.println(toChinese("123"));
System.out.println(toChinese("1210"));
System.out.println(toChinese("12"));
System.out.println(toChinese("1"));
System.out.println(toChinese("2001"));
System.out.println(toChinese("1001001"));
System.out.println(toChinese("10000001"));
}
/**
* 将八位数以内的转为中文;如果需要更高位数只用再加一次判断即可
* @param num
* @return
*/
static String toChinese(String num) {
StringBuffer sb = new StringBuffer();
if (num.length() <= 4) {
return toFourChinese(num);
} else if (num.length() > 4 && num.length() <= 8) {
String a = num.substring(0, num.length() - 4);
sb.append(toFourChinese(a));
sb.append("万");
String b = num.substring(num.length() - 4, num.length());
sb.append(toFourChinese(b));
return sb.toString();
} else {
return "";
}
}
/**
* 将四位数以内的转换为中文读法
* @param num
* @return
*/
static String toFourChinese(String num) {
StringBuffer sb = new StringBuffer();
String[] unit = {"", "十", "百", "千"};
char[] chineseNum = {'零', '一', '二', '三', '四', '五', '六', '七', '八', '九'};
String result = "";
char[] chars = num.toCharArray();
int a = chars.length;
int count = 0;
// 12
if (a == 2 && chars[0] == '1') {
sb.append(unit[1]);
if (chars[1] != '0') {
// 将字符转为对应的中文 例如: '1' -> 一 ;
sb.append(chineseNum[chars[1] - 48]);
}
} else {
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '0') {
count++;
continue;
}
if (count >= 1) {
sb.append(chineseNum[0]);
}
sb.append(chineseNum[chars[i] - 48]);
sb.append(unit[a - count - 1]);
a--;
}
}
result = sb.toString();
return result;
}
}