阿拉伯数字转中文

来源:互联网 发布:知商金融 红包 编辑:程序博客网 时间:2024/05/22 05:27
/** * 阿拉伯数字 中文数字转换 * Created by Admin on 2017/9/27. */public class NumToChineseUtil {    //数字位    static String[] CHN_NUMBER = {"零","一","二","三","四","五","六","七","八","九"};    //权位    static String[] CHN_UNIT = {"","十","百","千"};    //节权位    static String[] CHN_UNIT_SECTION = {"", "万", "亿", "万亿"};    /**     * 数字转中文     * @param num 阿拉伯数字     * @return 中文     */    public static String NumberToChinese(int num){        StringBuffer sb = new StringBuffer();        boolean needZero = false;        int pos = 0;        //0的话直接返回零        if(num == 0){           sb.insert(0,CHN_NUMBER[0]);        }        //大于0的话        while (num > 0){            int section = num % 10000;            if(needZero){                sb.insert(0,CHN_NUMBER[0]);            }            String sectionToChinese = SectionNumToChinese(section);            //判断是否需要节权位            sectionToChinese += (section !=0) ? CHN_UNIT_SECTION[pos] : CHN_UNIT_SECTION[0];            sb.insert(0, sectionToChinese);            needZero = ((section < 1000 && section > 0) ? true : false); //判断section中的千位上是不是为零,若为零应该添加一个零。            pos++;            num = num / 10000;        }        return sb.toString();    }    /**     * 将四位的section转换为中文数字     * @param section 权位     * @return 中文数字     */    public static String SectionNumToChinese(int section){        StringBuffer sb = new StringBuffer();        int unitPos = 0;//节权位编号,0-3 个十百千        boolean zero = true;//确保连续多个0,只补一个中文零        while (section > 0) {            int v = (section % 10);            if (v == 0) {                if ((section == 0) || !zero) {                    zero = true; /*需要补0,zero的作用是确保对连续的多个0,只补一个中文零*/                    //chnStr.insert(0, chnNumChar[v]);                    sb.insert(0, CHN_NUMBER[v]);                }            } else {                zero = false; //至少有一个数字不是0                StringBuffer tempStr = new StringBuffer(CHN_NUMBER[v]);//数字v所对应的中文数字                tempStr.append(CHN_UNIT[unitPos]);  //数字v所对应的中文权位                sb.insert(0, tempStr);            }            unitPos++; //移位            section = section / 10;        }        return sb.toString();    }}

原创粉丝点击