用逗号格式化 BigDecimal 数字,最多 2 个小数位

问题描述

我想用逗号和 2 个小数位格式化 BigDecimal 数字。 如果 BigDecimal 数中的十进制值为 0,那么我也想删除尾随零。 例如 金额为 20000.00,应格式化为 20,000 金额为 167.50,应格式化为 167.50 金额为 20000.75,应格式化为 20,000.75

我用过这个方法-

public static String getNumberFormattedString(BigDecimal bigDecimal) {
        if (bigDecimal != null) {
            NumberFormat nf = NumberFormat.getInstance(new Locale("en","IN"));
            nf.setMinimumFractionDigits(0);
            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);
            return nf.format(bigDecimal);
        }
        return "";
    }

这不会为大十进制输入 167.50 返回正确的输出。 格式化输出为 167.5

解决方法

您可以根据需要使用 NumberFormat。这是我使用的函数:

   public static String GenerateFormat(Double value) {
        if (value == null) return "";
        NumberFormat nf = NumberFormat.getInstance(new Locale("de","DE"));
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(2);
        nf.setGroupingUsed(true);
        return nf.format(value);
    }

在这里,您可以看到我提供 Locale 作为 NumberFormat 的参数。每个国家/地区都有自己的数字格式标准,使用此语言环境 new Locale("en","US") 可以实现您想要的。在 setMaximumFractionDigits 中,您可以放置​​您想要的小数位数,在您的情况下为 2。

编辑

根据你的情况,试试这个:

   public static String GenerateFormat(Double value) {
        if (value == null) return "";
        NumberFormat nf = NumberFormat.getInstance(new Locale("de","DE"));
        if (value%1 == 0) nf.setMinimumFractionDigits(0);
        else nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);
        nf.setGroupingUsed(true);
        return nf.format(value);
    }