如何在不舍入的情况下格式化 Java 中的双输入?

How do I format double input in Java WITHOUT rounding it?

我读过这个问题Round a double to 2 decimal places 它显示了如何舍入数字。我想要的只是简单的格式化,只打印两位小数。 我拥有的和尝试过的:

double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(res)); //prints 24.70 and I want 24.69
System.out.println("Total: " + String.format( "%.2f", res )); //prints 24.70

所以当我有 24.695999999999998 时,我想将其格式化为 24.69

你需要先取double值的floor - 然后格式化它。

Math.floor(double)

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

所以使用类似的东西:

double v = Math.floor(res * 100) / 100.0;

其他替代方法包括使用 BigDecimal

public void test() {
    double d = 0.29;
    System.out.println("d=" + d);
    System.out.println("floor(d*100)/100=" + Math.floor(d * 100) / 100);
    System.out.println("BigDecimal d=" + BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}

打印

d=0.29
floor(d*100)/100=0.28
BigDecimal d=0.29

除了使用Math.floor(double) and calculating a scale (e.g. * 100 and then / 100.0 for two decimal points) you could use BigDecimal, then you can invoke setScale(int, int)喜欢

double res = 24.695999999999998;
BigDecimal bd = BigDecimal.valueOf(res);
bd = bd.setScale(2, RoundingMode.DOWN);
System.out.println("Value: " + bd);

哪个也会给你(要求的)

Value: 24.69

将数字乘以 100 并将其转换为整数。这会切断除您想要的两个以外的所有小数位。将结果除以 100.00。 (24.69).

int temp = (int)(res * 100);
double result = temp / 100.00;

或一行代码中的相同内容:

double result = ((int)(res * 100)) / 100.00;