数字金额转中文大写(优化版)

℡╲_俬逩灬. 提交于 2019-12-14 11:13:04

题目描述:将阿拉伯数字金额转成中文大写表示

优化之后的源代码如下:

import java.math.BigDecimal;

/**
 * @author zhenqinl
 * @date 2019/12/13
 * @describe 数字金额转换Api
 */
public class AmountTransApi {
    private static  String[] tmp = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static String[] unit = {"仟","佰","拾","","角","分","厘"};
    public static void main(String[] args){
        String endans = "";
        String str = "10009212.24";
        endans = getBigword(str);
        System.out.println(endans);
    }
    public static String getBigword(String money) {
        String ans = "";
        if(new BigDecimal(money).compareTo(BigDecimal.ZERO) == 0){
           return "零圆整"; }
        String sp = "";
        String[] fuck = new String[0];
        if (money.contains(".")) {
            fuck = money.split("\\.");
            sp = fuck[0];
        }else{ sp = money;
        }
        // 翻译小数点之前的数字
        if (sp.length() > 8) {
                ans = ans + getAllWord(sp.substring(0, sp.length() - 8)) + "亿";
                ans = ans + getAllWord(sp.substring(sp.length() - 8, sp.length() - 4)) + "万";
                ans = ans + getAllWord(sp.substring(sp.length() - 4)) + "圆";
           }else if (sp.length() > 4) {
                ans = ans + getAllWord(sp.substring(0, sp.length() - 4)) + "万";
                ans = ans + getAllWord(sp.substring(sp.length() - 4)) + "圆";
            }else if(!getAllWord(sp).equals("")){
               ans = ans + getAllWord(sp)+"圆";
        }
        // 翻译小数点后数字
        if (money.contains(".")&&new BigDecimal(fuck[1]).compareTo(BigDecimal.ZERO) != 0) {
            String midsp = fuck[1];
            if (fuck[1].length() > 3) {
                midsp = fuck[1].substring(0, 3); }
            int temp = 0 ;
            for (int i = 0; i < midsp.length(); i++) {
                temp = Integer.parseInt(String.valueOf(midsp.charAt(i)));
                if(temp != 0){
                    ans = ans + tmp[temp] + unit[i+4]; }
            }
        }else{ ans = ans + "整"; }
            return ans;
    }
    public static String getAllWord(String sp){
        String answer = "";
        if (sp.length() == 4 && Long.parseLong(sp) % 1000 == 0) {
            return answer + tmp[(int) Long.parseLong(sp) / 1000] + "仟"; }
        int temp = 0;
        int acount = 0;
        int midtemp = 0;
        for (int i = 4 - sp.length(); i < 4; i++) {
            temp = Integer.parseInt(String.valueOf(sp.charAt(midtemp++)));
            if (temp != 0) {
                answer = answer + tmp[temp] + unit[i];
                acount = 0;
            } else if (acount == 0 && i != 3) {
                answer = answer + "零";
                acount = 1; }
        }
        return answer;
        }
}

整理不易~~

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!