美文网首页
Android 金额转大写

Android 金额转大写

作者: 随风流逝 | 来源:发表于2017-08-15 12:52 被阅读35次

    iOS写完之后顺便把android也写了,凑合着用吧,一样的避免了像什么零佰、零仟这种情况,还有壹仟壹圆、壹万壹佰这种情况,写的略麻烦,不过可以凑合用

    /**
         * 数字金额大写转换
         * 要用到正则表达式
         */
        public static String digitUppercase(String money){
            if (money.length() == 0)
                return "";
            if (Double.parseDouble(money) == 0)
                return "零圆整";
    
            String fraction[] = {"角", "分"};
            String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            String unit[][] = {{"圆", "万", "亿"}, {"", "拾", "佰", "仟"}};
    
            String [] numArray = money.split("\\.");
    
            String amountInWords = "";
    
            double n = Double.parseDouble(money);
            int integerPart = (int)Math.floor(n);
    
            for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
                String temp ="";
                int tempNum = integerPart%10000;
                if (tempNum != 0 || i == 0) {
                    for (int j = 0; j < unit[1].length && integerPart > 0; j++) {
                        temp = digit[integerPart%10]+unit[1][j] + temp;
                        integerPart = integerPart/10;
                    }
                    /*
                     *正则替换,加上单位
                     *把零佰零仟这种去掉,再去掉多余的零
                     */
                    amountInWords = temp.replaceAll("(零.)+", "零").replaceAll("^$", "零").replaceAll("(零零)+", "零") + unit[0][i] + amountInWords;
                } else {
                    integerPart /= 10000;
                    temp = "零";
                    amountInWords = temp + amountInWords;
                }
                amountInWords = amountInWords.replace("零" + unit[0][i], unit[0][i] + "零");
                if (i > 0) amountInWords = amountInWords.replace("零" + unit[0][i-1], unit[0][i-1] + "零");
            }
    
            String fWordsStr = "";
            if (numArray.length > 1) {
                String fStr = numArray[1];
                int iLen = fraction.length < fStr.length() ? fraction.length : fStr.length();
                for (int i = 0; i < iLen; i++) {
                    int numInt = Integer.parseInt(fStr.substring(i, i+ 1));
                    if (numInt == 0) continue;
                    if (amountInWords.length() > 0 && fWordsStr.length() == 0 && i > 0)
                        fWordsStr = "零";
                    fWordsStr += (digit[numInt] + fraction[i]);
                }
            }
            if (fWordsStr.length() == 0) fWordsStr = "整";
            amountInWords = amountInWords + fWordsStr;
            amountInWords = amountInWords.replaceAll("(零零)+", "零").replace("零整", "整");
    
            return  amountInWords;
        }
    

    iOS版的有需要可以看一下:http://www.jianshu.com/p/c6b9f6dc3a96

    相关文章

      网友评论

          本文标题:Android 金额转大写

          本文链接:https://www.haomeiwen.com/subject/aswmrxtx.html