wuzeyu
2024-06-11 a3b3610216dfeb82c729c914dbb2018da7eb54ef
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.dy.pipIrrGlobal.util;
 
import java.math.BigDecimal;
 
/**
 * @author ZhuBaoMin
 * @date 2024-02-01 9:58
 * @LastEditTime 2024-02-01 9:58
 * @Description 金额数字转中文大写
 */
public class AmountToChinese {
    private static final String[] CN_UPPER_NUMBER = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
    private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
    private static final String CN_FULL = "整";
    private static final String CN_NEGATIVE = "负";
    private static final int MONEY_PRECISION = 2;
    private static final String CN_ZEOR_FULL = "零元" + CN_FULL;
 
    public static String toChinese(BigDecimal amount) {
        StringBuilder result = new StringBuilder();
        amount = amount.setScale(MONEY_PRECISION, BigDecimal.ROUND_HALF_UP);
        long number = amount.movePointRight(MONEY_PRECISION).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
        boolean zero = true;
        int unitIndex = 0;
        if (number == 0) {
            return CN_ZEOR_FULL;
        }
        if (number < 0) {
            number = -number;
            result.append(CN_NEGATIVE);
        }
        long scale = 10;
        while (true) {
            if (number == 0) {
                break;
            }
            long numIndex = number % scale;
            if (zero && numIndex == 0) {
                zero = false;
            }
            if (numIndex != 0) {
                result.insert(0, CN_UPPER_MONETRAY_UNIT[unitIndex])
                        .insert(0, CN_UPPER_NUMBER[(int) numIndex]);
                zero = false;
            }
            else if (!zero) {
                result.insert(0, CN_UPPER_NUMBER[(int) numIndex]);
            }
            number = number / scale;
            unitIndex++;
        }
        if (zero) {
            result.append(CN_FULL);
        }
        return result.toString();
    }
}