将金额转换为中文大写
思路
判断符号,0则直接返回数字去掉点00结尾的要加’整’循环,从后面每次取一个数位上的值直到最前面,若是非零则加上对应的数值和单位若是零,判断上一个是否为零,是,则不加’零’,若是个位上的需要加’‘元’若是万,亿,兆则要加上’万,亿,兆’,要排除出现’亿万和兆亿’(数值除以10000)package com.mon.utils;import java.math.BigDecimal;import java.util.Arrays;import java.util.Random;import java.util.Scanner;import javax.swing.plaf.ViewportUI;import org.apache.xalan.templates.ElemAttributeSet;import org.apache.xmlbeans.impl.xb.xsdschema.Public;import org.junit.Test;import com.sun.media.jai.iterator.RectIterCSM;/*** 数据处理* * @author hwq* @date 10月10日*/public class MyDigitUtils {private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };private static final String[] CN_UPPER_MONETRAY_UNIT = {"分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾","佰", "仟", "兆", "拾", "佰", "仟" };/*** 将金额转换为大写中文* * @param money* @return*/public static String number2CNMoneyUnit(double money) {StringBuffer sbBuffer = new StringBuffer();BigDecimal bigDecimalMoney = BigDecimal.valueOf(money);int signum = bigDecimalMoney.signum();if (signum == 0) {return "零元整";}long number = bigDecimalMoney.setScale(2, BigDecimal.ROUND_HALF_UP).abs().movePointRight(2).longValue();int numIndex = 0;int numUnit = 0;boolean getZero = false;if (number % 100 == 0) {sbBuffer.append("整");number=number/100;numIndex = 2;getZero = true;} while (true) {if (number == 0) {break;}numUnit = (int) (number % 10);if (numUnit == 0) {if (getZero) {if (numIndex == 2) {sbBuffer.insert(0, "元");} else if ((numIndex - 2) % 4 == 0 && number % 10000 != 0) {sbBuffer.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);}}else {if(numIndex!=0){//最后一位不加零sbBuffer.insert(0, "零");}getZero = true;} else {sbBuffer.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);sbBuffer.insert(0, CN_UPPER_NUMBER[numUnit]);getZero = false;}number = number / 10;numIndex++;}if (signum < 0) {sbBuffer.insert(0, "负");}return sbBuffer.toString();}}
测试
public static void main(String[] args) {Random random=new Random();for(int i=0;i<50;i++) {double nextDouble = random.nextDouble()*Math.pow(10,CN_UPPER_MONETRAY_UNIT.length-5);System.out.print(BigDecimal.valueOf(nextDouble)+"----");System.out.println(MyDigitUtils.number2CNMoneyUnit(nextDouble));}