首先,定义一系列的常量,包括0~9对应的大写汉字、单位、“整”、零元整、负数、四舍五入后精确的位数:
private static final String[] CN_UPPER_NUMBER = { "零", "壹", "贰", "叁", "肆","伍", "陆", "柒", "捌", "玖" };private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元","拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾","佰", "仟" };private static final String CN_FULL = "整";private static final String CN_NEGATIVE = "负";private static final int MONEY_PRECISION = 2;private static final String CN_ZEOR_FULL = "零元" + CN_FULL;
然后,编写转换方法的代码,这里一般要求传入的参数是BigDecimal类型,因为该类型更能表示货币金额的精确性。如果从前端接收来的数据是String型也可以通过BigDecimal提供的构造方法来转换为BigDecimal。这里主要写数字转为大写的方法:
public static String numberToCNMontrayUnit(BigDecimal numberOfMoney) {StringBuffer sb = new StringBuffer();// 返回numberOfMoney的正负号:-1--负数,0--0,1--正数int signum = numberOfMoney.signum();// 零元整的情况if (signum == 0) {return CN_ZEOR_FULL;}// 这里会进行金额的四舍五入long number = numberOfMoney.movePointRight(MONEY_PRECISION).setScale(0,4).abs().longValue();// 得到小数点后两位值long scale = number % 100;int numUnit = 0;int numIndex = 0;boolean getZero = false;// 判断最后两位数,一共有四种情况:00 = 0, 01 = 1, 10, 11if (!(scale > 0)) {numIndex = 2;number = number / 100;getZero = true;}if ((scale > 0) && (!(scale % 10 > 0))) {numIndex = 1;number = number / 10;getZero = true;}int zeroSize = 0;while (true) {if (number <= 0) {break;}// 每次获取到最后一个数numUnit = (int) (number % 10);if (numUnit > 0) {if ((numIndex == 9) && (zeroSize >= 3)) {sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);}if ((numIndex == 13) && (zeroSize >= 3)) {sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);}sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);sb.insert(0, CN_UPPER_NUMBER[numUnit]);getZero = false;zeroSize = 0;} else {++zeroSize;if (!(getZero)) {sb.insert(0, CN_UPPER_NUMBER[numUnit]);}if (numIndex == 2) {if (number > 0) {sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);}} else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) {sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);}getZero = true;}// 让number每次都去掉最后一个数number = number / 10;++numIndex;}// 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负if (signum == -1) {sb.insert(0, CN_NEGATIVE);}// 输入的数字小数点后两位为"00"的情况,则要在最后追加特殊字符:整if (!(scale > 0)) {sb.append(CN_FULL);}return sb.toString();}