double f = 111231.5585; 需保留兩位小數 → 111231.56System.out.println(String.format("%.2f", f)); // 111231.56
// %.2f 解析:% 佔位符、.2 兩位小數、f 浮點數
String,後續運算需再轉型DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f)); // 111231.56
// 模式說明:
// #.00 → 兩位小數,整數部不補零
// 0.00 → 兩位小數,整數部不足補零
// #,##0.00 → 含千分位分隔符
BigDecimal bd = new BigDecimal(String.valueOf(f));
BigDecimal result = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(result); // 111231.56
double d1 = (double) Math.round(f * 100) / 100; // 111231.56
// 保留 4 位:Math.round(f * 10000) / 10000.0
double 可直接運算| 方法 | 回傳型別 | 精度 | 效能 | 適用場景 |
|---|---|---|---|---|
| String.format | String | 四捨五入 | 中 | 單純顯示、日誌輸出 |
| DecimalFormat | String | 四捨五入 | 中 | 複雜格式(千分位、貨幣符號) |
| BigDecimal | BigDecimal | 精確 | 低 | 金融計算、精度敏感業務 |
| Math.round | double | 四捨五入 | 高 | 高頻運算、非金融數值 |
<bean:write name="entity" property="dkhAFSumPl" format="0.00" />
public class NumberFormatDemo {
public static void main(String[] args) {
double sd = 23.2558896635;
// Math.round 乘除法
System.out.println("4位小數:" + (double) Math.round(sd * 10000) / 10000.0);
// DecimalFormat
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df3 = new DecimalFormat("##.000");
System.out.println("2位小數:" + df2.format(sd)); // 23.26
System.out.println("3位小數:" + df3.format(sd)); // 23.256
}
}
輸出:
4位小數:23.2559
2位小數:23.26
3位小數:23.256