天天看點

數字金額轉中文大寫(優化版)

題目描述:将阿拉伯數字金額轉成中文大寫表示

優化之後的源代碼如下:

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;
        }
}
           

整理不易~~

數字金額轉中文大寫(優化版)