如何在Java中格式化双输入而不进行舍入?

我已经阅读了这个问题,将一个小数加倍到2位小数它显示了如何舍入数字。 我想要的只是简单的格式化,只打印两个小数位。 我有什么和我尝试过的:

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

您需要首先考虑双倍值 – 然后格式化它。

Math.floor(双)

返回小于或等于参数且等于数学整数的最大(最接近正无穷大)double值。

所以使用类似的东西:

 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)和计算比例(例如* 100然后/ 100.0为两个小数点)你可以使用BigDecimal ,然后你可以调用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;