【问题标题】:Format, 2 decimal places for double and 0 for integer in java格式,Java 中的双精度和整数的 2 位小数和 0
【发布时间】:2016-09-01 09:22:43
【问题描述】:

如果有分数,我正在尝试将双精度格式化为精确的 2 位小数,否则使用 DecimalFormat 将其截断

所以,我想实现下一个结果:

100.123 -> 100.12
100.12  -> 100.12
100.1   -> 100.10
100     -> 100

变体 #1

DecimalFormat("#,##0.00")

100.1 -> 100.10
but
100   -> 100.00

变体 #2

DecimalFormat("#,##0.##")

100   -> 100
but
100.1 -> 100.1

有什么想法在我的情况下选择什么模式?

【问题讨论】:

标签: java format decimal decimalformat


【解决方案1】:

我达到的唯一解决方案是使用这里提到的 if 语句:https://stackoverflow.com/a/39268176/6619441

public static boolean isInteger(BigDecimal bigDecimal) {
    int intVal = bigDecimal.intValue();
    return bigDecimal.compareTo(new BigDecimal(intVal)) == 0;
}

public static String myFormat(BigDecimal bigDecimal) {
    String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00";
    return new DecimalFormat(formatPattern).format(bigDecimal);
}

测试

myFormat(new BigDecimal("100"));   // 100
myFormat(new BigDecimal("100.1")); // 100.10

如果有人知道更优雅的方式,请分享!

【讨论】:

    【解决方案2】:

    我相信我们需要一个 if 语句。

    static double intMargin = 1e-14;
    
    public static String myFormat(double d) {
        DecimalFormat format;
        // is value an integer?
        if (Math.abs(d - Math.round(d)) < intMargin) { // close enough
            format = new DecimalFormat("#,##0.##");
        } else {
            format = new DecimalFormat("#,##0.00");
        }
        return format.format(d);
    }
    

    应根据情况选择一个数字被视为整数所允许的余量。只是不要假设你总是有一个精确的整数,当你期望一个时,双打并不总是这样。

    使用上述声明myFormat(4) 返回4myFormat(4.98) 返回4.98myFormat(4.0001) 返回4.00

    【讨论】:

    • 我也有过使用if语句的想法,但希望能更优雅地解决,使用DecimalFormat和特定模式。
    • 您可以创建DecimalFormat 的子类并将if 语句放在子类中。不过,我不确定我是否真的喜欢这个主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多