class RMB {
    private static final String[] NUMBER = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
    private static final String[] UNIT = {'', '拾', '佰', '仟'};
    private static final String[] BIG_UNIT = {'', '万', '亿', '万亿'};

    public static String toString(double x) {
        long num = (long) x;
        int decimal = (int) Math.round((x - num) * 100);

        StringBuilder result = new StringBuilder();
        result.append(convertInteger(num));
        if (decimal != 0) {
            result.append(convertDecimal(decimal));
        } else {
            result.append('整');
        }

        return result.toString();
    }

    private static String convertInteger(long num) {
        StringBuilder result = new StringBuilder();

        if (num == 0) {
            result.append(NUMBER[0]);
        } else {
            int unitIndex = 0;
            while (num > 0) {
                int n = (int) (num % 10);
                if (n != 0) {
                    result.insert(0, UNIT[unitIndex]);
                    result.insert(0, NUMBER[n]);
                } else if (result.length() > 0 && result.charAt(0) != '零') {
                    result.insert(0, NUMBER[0]);
                }
                num /= 10;
                unitIndex++;
            }
        }

        return result.toString();
    }

    private static String convertDecimal(int decimal) {
        StringBuilder result = new StringBuilder();

        int unitIndex = 0;
        while (decimal > 0) {
            int n = decimal % 10;
            if (n != 0) {
                result.insert(0, UNIT[unitIndex]);
                result.insert(0, NUMBER[n]);
            } else if (result.length() > 0 && result.charAt(0) != '零') {
                result.insert(0, NUMBER[0]);
            }
            decimal /= 10;
            unitIndex++;
        }
        result.insert(0, '角');
        result.insert(0, NUMBER[0]);
        result.insert(0, '分');

        return result.toString();
    }
}

该 Java 类 RMB 提供了一个静态方法 toString,可以将给定的千万亿以内的数值转换为大写的人民币金额表达方式。例如,输入 1137.48,返回值为:壹仟壹佰叁拾柒元肆角捌分。该工具考虑了以下情况:

  1. 整数金额省略小数部分,添加“整”字。例如,123返回值为“壹佰贰拾叁元整”;
  2. 若金额中含有连续的0,则只写一个零。例如,10005返回值为“壹万零伍元整”;
  3. 10的省略表示形式。例如,110返回值为“壹佰壹拾元整”,而10返回值为“拾元整”。

该工具使用字符串相关类实现,并遵循良好的编码规范,使其易于理解和维护。

Java实现人民币金额转大写字符串工具

原文地址: https://www.cveoy.top/t/topic/cq0q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录