java 金额转为中文大写

网上没看到合适的,自己写了个。

public class ChineseCapitalUtil {
    
    

    private final static String[] number = {
    
    "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private final static String[] INTEGER_UNIT = {
    
    "拾", "佰", "仟"};
    private final static String[] DECIMAL_UNIT = {
    
    "角", "分"};
    private final static String[] RADICES_UNIT = {
    
    "元", "万", "亿"};
    private final static Pattern NUMBER_PATTERN = Pattern.compile("^(([1-9]\\d*(\\.(\\d){1,2}))|(0\\.(\\d){1,2}))$");
    private final static char baseChar='0';

    /**
     * 将金额转为中文大写
     * @param origin
     * @return {@link String}
     */
    public static String convert(String origin) {
    
    
        // 校验参数合法性
        if (!NUMBER_PATTERN.matcher(origin).matches()) {
    
    
            return "";
        }
        StringBuilder builder = new StringBuilder();
        String[] splitArray = origin.split("\\.");
        // 处理整数
        convertInteger(splitArray[0], builder);
        // 处理小数
        convertDecimal(splitArray, builder);
        return builder.toString();
    }

    private static void convertInteger(String str, StringBuilder builder) {
    
    
        // 对于0.xx的直接跳过整数
        if (str.length() == 1 && str.charAt(0) == baseChar) {
    
    
            return;
        }
        int loop = 0;
        int zero = 0;
        int radicesIndex = (str.length() - 1) / 4;
        // 不足4位则以实际长度循环
        int len = Math.min(str.length(), 4);
        while (loop < str.length()) {
    
    
            for (int i = 0; i < len; i++) {
    
    
                char c = str.charAt(loop);
                if (c == baseChar) {
    
    
                    zero++;
                } else {
    
    
                    if (zero > 0) {
    
    
                        zero = 0;
                        builder.append(number[0]);
                    }
                    builder.append(number[c - baseChar]);
                    int integerIndex = (str.length() - loop - 1) % 4;
                    if (integerIndex > 0) {
    
    
                        builder.append(INTEGER_UNIT[integerIndex - 1]);
                    }
                }
                loop++;
            }
            builder.append(RADICES_UNIT[radicesIndex--]);
        }
    }

    private static void convertDecimal(String[] splitArray, StringBuilder builder) {
    
    
        if (splitArray.length > 1) {
    
    
            int decimalIndex = splitArray[1].length();
            for (int i = 0; i < decimalIndex; i++) {
    
    
                // 跳过0
                if (splitArray[1].charAt(i) == baseChar) {
    
    
                    continue;
                }
                char c = splitArray[1].charAt(i);
                builder.append(number[c - baseChar]).append(DECIMAL_UNIT[i]);
            }
        } else {
    
    
            builder.append("整");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34789577/article/details/109103521