UpperNumTool.java
import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 实现数字的大写转换
*
* @author Lshare
* @version V1.0
*/
public class UpperNumTool {
private static String[] upperNums = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
private static String[] units = { "", "十", "佰", "仟", "万", "亿", "兆" ,"京","垓"};
public static String upperNum(BigInteger num) {
String shortNum = num.toString();
StringBuilder sb = new StringBuilder();
// 反转字符串,存储到int数组中
int[] nums = new int[shortNum.length()];
shortNum = new StringBuilder(shortNum).reverse().toString();
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.valueOf(shortNum.charAt(i) + "");
}
// 数字大写化
for (int i = 0; i < nums.length; i++) {
if (i % 4 != 0) {
if (nums[i] != 0) {
sb.append(units[i % 4]).append(upperNums[nums[i]]);
} else {
sb.append(upperNums[nums[i]]);
}
} else if (i % 4 == 0) {
if (i != 0) {
sb.append(units[i / 4 + 3]).append(nums[i] == 0 ? "" : upperNums[nums[i]]);
} else {
sb.append(upperNums[nums[i]]);
}
}
}
// 去除首尾的零
while (sb.toString().startsWith(upperNums[0]) || sb.toString().endsWith(upperNums[0])) {
if (sb.toString().startsWith(upperNums[0]))
sb.deleteCharAt(0);
if (sb.toString().endsWith(upperNums[0]))
sb.deleteCharAt((sb.length() - 1));
}
// 去除中间多余的零
Pattern p = Pattern.compile("(零){2,}");
Matcher m = p.matcher(sb);
if (m.find()) {
String str = sb.toString().replace(m.group(), upperNums[0]);
sb = new StringBuilder(str);
}
// 去除万、亿、兆等前的零
for (int i = 4; i < units.length; i++) {
if (upperNums[0].equals(sb.charAt(sb.indexOf(units[i]) + 1) + "")) {
sb.deleteCharAt(sb.indexOf(units[i]) + 1);
}
}
return sb.reverse().toString();
}
}
通过调用这个类,可以实现下面的效果: