一、 返回double
1. 四舍五入
double d = 12.345; d = (double) Math.round(d * 100) / 100; System.out.println(d);
2. 自行選擇處理方式
double d = 12.345; BigDecimal b = new BigDecimal(d); d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(d);
二、 返回String
1. 去掉尾數
double d = 114.145; DecimalFormat df = new DecimalFormat("#.00"); String str = df.format(d); System.out.println(str);
2. 四舍五入
double d = 114.145; String.format("%.2f", d);
3. 自行選擇處理方式
double d = 114.145 NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); nf.setRoundingMode(RoundingMode.HALF_UP); System.out.println(nf.format(d));
注:UP進位處理(直接+1),DOWN去掉尾數,HALF_UP四舍五入,HALF_DOWN五舍六入