Java handles amount case conversion

Scenario: Many times our business scenarios involve amounts, and we need to handle case conversion of amounts, such as the amount displayed in electronic invoices, the amount displayed in electronic insurance policies, etc. How can we use Java code to convert this elegantly and easily? This is also a very good topic related to data structures and algorithms, and it is worth studying the ideas carefully.

 /**
     * 大小写金额转换
     * @param n
     * @return
     */
    public static String digitUppercase(double n) {
    
    
        String fraction[] = {
    
     "角", "分" };
        String digit[] = {
    
     "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
        String unit[][] = {
    
     {
    
     "元", "万", "亿" }, {
    
     "", "拾", "佰", "仟" } };

        String head = n < 0 ? "负" : "";
        n = Math.abs(n);

        String s = "";
        for (int i = 0; i < fraction.length; i++) {
    
    
            //优化double计算精度丢失问题
            BigDecimal nNum = new BigDecimal(n);
            BigDecimal decimal = new BigDecimal(10);
            BigDecimal scale = nNum.multiply(decimal).setScale(2, RoundingMode.HALF_EVEN);
            double d = scale.doubleValue();
            s += (digit[(int) (Math.floor(d * Math.pow(10, i)) % 10)] + fraction[i])
                    .replaceAll("(零.)+", "");
        }
        if (s.length() < 1) {
    
    
            s = "整";
        }
        int integerPart = (int) Math.floor(n);

        for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
    
    
            String p = "";
            for (int j = 0; j < unit[1].length && n > 0; j++) {
    
    
                p = digit[integerPart % 10] + unit[1][j] + p;
                integerPart = integerPart / 10;
            }
            s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i]
                    + s;
        }
        return head
                + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "")
                .replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
    }

test:

 public static void main(String[] args) {
    
    
        System.out.println(digitUppercase(124.4));
    }

result:

壹佰贰拾肆元肆角

Guess you like

Origin blog.csdn.net/weixin_47061482/article/details/132056651