Android 金额转大写

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 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,466评论 25 708
  • 因项目需要把数字金额转为大写,在网上搜了一些这方面的文章,都不尽如意,会出现各种各样的问题,有像什么零佰、零仟这种...
    随风流逝阅读 1,364评论 0 3
  • 巅峰的孤独源于爱的缺乏。 想要爱情,首先要有能力去爱,,至于回事那个正确的人我无从而知,爱情和理智
    owte阅读 87评论 0 0
  • 文/明道副总裁许维 公众号/xuwei0418 本周最大的科技新闻就是——朋友圈广告来了! 有人说朋友圈广告意味着...
    头头是道许维阅读 593评论 0 4