public class NumberUtils {
public static int UNIT_STEP = 4;
public static String[] CN_UNITS = new String[]{"个", "十", "百", "千", "万", "十",
"百", "千", "亿", "十", "百", "千", "万"};
public static String[] CN_CHARS = new String[]{"零", "一", "二", "三", "四",
"五", "六", "七", "八", "九"};
public static String getCNNum(int srcNum) {
String desCNNum = "";
if (srcNum <= 0) {
desCNNum = "零";
} else {
int singleDigit;
while (srcNum > 0) {
singleDigit = srcNum % 10;
desCNNum = String.valueOf(CN_CHARS[singleDigit]) + desCNNum;
srcNum /= 10;
}
}
return desCNNum;
}
public static String cvt(long num) {
return cvt(num, false);
}
public static String cvt(String num, boolean isColloquial) {
int integer, decimal = 0;
StringBuffer strs = new StringBuffer(32);
String[] splitNum = num.split("\\.");
integer = Integer.parseInt(splitNum[0]);
if (splitNum.length > 1) {
decimal = Integer.parseInt(splitNum[1]);
}
String[] result_1 = convert(integer, isColloquial);
for (String str1 : result_1) {
strs.append(str1);
}
if (decimal == 0) {
return strs.toString();
} else {
String result_2 = getCNNum(decimal);
strs.append("点");
strs.append(result_2);
return strs.toString();
}
}
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[] convert(long num, boolean isColloquial) {
if (num < 10) {
return new String[]{CN_CHARS[(int) num]};
}
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'];
int unitPos = chars.length - pos - 1;
String cnUnit = CN_UNITS[unitPos];
boolean isZero = (ch == '0');
boolean isZeroLow = (pos + 1 < chars.length && chars[pos + 1] == '0');
boolean 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))) {
cnchars.add(CN_CHARS[0]);
}
}
if (isUnitStep || !isZero) {
cnchars.add(cnUnit);
isLastUnitStep = isUnitStep;
}
if (isZero && (isZeroLow || isUnitStep)) {
continue;
}
cnchars.add(cnChar);
isLastUnitStep = false;
}
Collections.reverse(cnchars);
int 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[]{});
}
}