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

Format BigDecimal number with commas upto 2 decimal places

我想用逗号和两位小数来格式化 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);
    }