在 Java 開發中,針對浮點數進行小數位數控制是常見需求。本文整理四種主流方法,並提供完整程式碼範例供參考。
最簡單的方式是利用 String.format() 格式化輸出:
double x1 = 111231.5585;
double x2 = 3.1415926;
System.out.println(String.format("%.2f", x1)); // 輸出:111231.56
System.out.println(String.format("%.2f", x2)); // 輸出:3.14
%.2f 表示保留兩位小數,四捨五入。
DecimalFormat 提供更靈活的格式化模式:
import java.text.DecimalFormat;
public void formatDemo() {
double f = 111231.5585;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f)); // 輸出:111231.56
// 模式說明:
// #.00 保留兩位小數
// #.0000 保留四位小數
// 以此類推
}
透過乘除與四捨五入實現精確控制:
double sd = 23.2558896635;
// 保留四位小數
double d1 = (double) (Math.round(sd * 10000) / 10000.0);
double d2 = (double) (Math.round(sd * 10000) / 10000.0000000000);
System.out.println("四位小數測試:" + d1); // 23.2559
System.out.println("四位小數測試:" + d2); // 23.2559
在 JSP 頁面中使用 Struts 標籤:
<bean:write name="entity" property="dkhAFSumPl" format="0.00" />
import java.text.DecimalFormat;
public class NumberFormatDemo {
public static void main(String[] args) {
double sd = 23.2558896635;
// 方法一:Math.round
double d1 = (double) (Math.round(sd * 10000) / 10000.0);
System.out.println("四位小數:" + d1);
// 方法二:DecimalFormat
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df3 = new DecimalFormat("##.000");
System.out.println("兩位小數:" + df2.format(sd)); // 23.26
System.out.println("三位小數:" + df3.format(sd)); // 23.256
}
}
四位小數測試:23.2559
四位小數測試:23.2559
三位小數:23.256
兩位小數:23.26
建議:一般情況下推薦使用 DecimalFormat 或 String.format(),程式碼可讀性較佳;若需高效能數值運算,可考慮 Math.round() 配合乘除。