金额大小写转换工具类

package app.pattern;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 还是有点小bug,超过1亿后就会出现小问题;
 * 金额大小写转换工具类
 * @author muyx
 */
public class FigureTransformUtil {
	//金额大写数组,和数组下标对应
	private static final String numberChineseUppercase[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
	//金额单位
	private static final String units[] = { "分", "角", "元", "", "拾", "百", "千", "万", "拾", "百", "千", "亿", "拾", "百", "千",
			"万", "拾", "百", "千" };
	private static final String pattern = "#,###.00";

	private static final DecimalFormat decimalFormat = new DecimalFormat(pattern);

	public static void main(String[] args) {
		String[] testData = { /*"12", "12.01", "102.00", "102.01", "100,000", "102,002.46", "12,000,003,034.90",
								*/"1230000000011111.45" };
		for (int i = 0; i < testData.length; i++) {
			System.out.println(toMoneyStyle(testData[i]));
			System.out.println(toChineseUppercase(testData[i]));
		}
	}

	public static String toMoneyStyle(double number) {
		return decimalFormat.format(number);
	}

	public static String toMoneyStyle(String number) {
		return toMoneyStyle(numberToBigDecimal(number).doubleValue());
	}

	public static String toChineseUppercase(String money) {
		BigDecimal bigDecimal = numberToBigDecimal(money);
		char[] charArray = bigDecimal.toString().toCharArray();
		StringBuilder chineseUppercase = new StringBuilder();
		String prefixZeroBuffer = "";

		for (int i = 0, len = charArray.length; i < len; i++) {
			//单位("分", "角", "元"....)数组的下标位置;
			int unitLocation = len - i - 1;
			if (charArray[i] != '.') {
				int point = Integer.valueOf(charArray[i] + "");
				if (point == 0) {
					if (unitLocation == 7 || unitLocation == 11 || unitLocation == 15) {//无论怎么都不能少的处理
						chineseUppercase.append(units[unitLocation]);
						prefixZeroBuffer = "";
					} else {
						prefixZeroBuffer = numberChineseUppercase[point];
					}
				} else {
					//当前位置不为0时,零的缓存+数字大写+单位
					chineseUppercase.append(prefixZeroBuffer).append(numberChineseUppercase[point])
							.append(units[unitLocation]);
					prefixZeroBuffer = "";
				}
			} else {
				chineseUppercase.append(units[unitLocation]);
				prefixZeroBuffer = "";
			}
		}
		return chineseUppercase.toString();
	}

	/**
	 * 格式检查,并转换成BigDecimal
	 */
	private static BigDecimal numberToBigDecimal(String moneyNumer) {
		BigDecimal money = null;
		moneyNumer = moneyNumer.trim().replaceAll(",", "");//替换千分位
		if (moneyNumer.indexOf(".") == -1)
			moneyNumer += ".00";
		String regex = "[+|-]?\\d+(\\.{1}\\d{2})?";
		if (moneyNumer.matches(regex) && (moneyNumer.length() - 1) < units.length) {
			money = new BigDecimal(moneyNumer);
		} else {
			throw new RuntimeException("金额格式不正确");
		}
		return money;
	}
}

 

你可能感兴趣的:(工具类)