Java 格式化数字为千分位表示

在昨天的基础上封装一哈,昨天的:https://www.cnblogs.com/engure/p/17087169.html

/**
 * 格式化数字为千分位表示
 *
 * @param value       数值,可为 String/六种数值类型/BigDecimal
 * @param fieldLength 保留的小数位数,为 null 时的默认规则:若 value 为 bigDecimal 则不进行设置,否则保留两位小数
 * @param delimiter   千分位分隔符,为空时默认为 ,
 * @return 格式化后的数据,比如 1,234,567.89
 */
public static String format(Object value, Integer fieldLength, String delimiter) {
    try {
        if (value == null) {
            throw new NullPointerException("数值不可为null");
        }

        BigDecimal bigDecimalVal;
        if (value instanceof BigDecimal) {
            bigDecimalVal = (BigDecimal) value;
            if (fieldLength != null) {
                bigDecimalVal = bigDecimalVal.setScale(fieldLength, RoundingMode.HALF_UP);
            }
        } else {
            bigDecimalVal = new BigDecimal(value.toString());
            if (fieldLength != null) {
                bigDecimalVal = bigDecimalVal.setScale(fieldLength, RoundingMode.HALF_UP);
            } else {
                bigDecimalVal = bigDecimalVal.setScale(2, RoundingMode.HALF_UP);
            }
        }

        if (!StringUtils.hasLength(delimiter)) {
            delimiter = ",";
        }

        NumberFormat instance = NumberFormat.getInstance();
        instance.setMinimumFractionDigits(bigDecimalVal.scale());
        String[] parts = instance.format(bigDecimalVal).split(",");
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            res.append(parts[i]);
            if (i != parts.length - 1) {
                res.append(delimiter);
            }
        }
        return res.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
posted @ 2023-02-03 15:16  egu0o  阅读(1553)  评论(0编辑  收藏  举报