小数点到最接近的10号

需要将我的答案舍入到最接近的10号。

double finalPrice = everyMile + 2.8; DecimalFormat fmt = new DecimalFormat("0.00"); this.answerField.setText("£" + fmt.format(finalPrice) + " Approx"); 

上面的代码将整数舍入到最接近的10,但它不会舍入小数。 例如2.44应舍入到2.40

将模式更改为硬编码最终零:

 double finalPrice = 2.46; DecimalFormat fmt = new DecimalFormat("0.0'0'"); System.out.println("£" + fmt.format(finalPrice) + " Approx"); 

现在,如果你正在操纵现实世界的钱,你最好不要使用double,而是使用int或BigInteger。

请改用BigDecimal

你真的,真的不想使用二元浮点来获取货币价值。

编辑: round()不允许您指定小数位,只有有效数字。 这是一个有点繁琐的技术,但它的工作原理(假设你想截断,基本上):

 import java.math.*; public class Test { public static void main(String[] args) { BigDecimal bd = new BigDecimal("20.44"); bd = bd.movePointRight(1); BigInteger floor = bd.toBigInteger(); bd = new BigDecimal(floor).movePointLeft(1); System.out.println(bd); } } 

我希望有一种更简单的方法可以做到这一点……

这输出2.40

 BigDecimal bd = new BigDecimal(2.44); System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2)); 

请尝试以下方法:

 double finalPriceRoundedToNearestTenth = Math.round(10.0 * finalPrice) / 10.0; 

编辑

尝试这个:

 double d = 25.642; String s = String.format("£ %.2f", Double.parseDouble(String.format("%.1f", d).replace(',', '.'))); System.out.println(s); 

我知道这是一种愚蠢的方式,但它确实有效。