方法一:
用String類的format方法
例如:
double x = 1.23456789
System.out.println(String.format("%.6f", x)); //表示四捨五入保留六位小數。
System.out.println(String.format("%.3f", x)); //表示四捨五入保留3位小數 輸出爲1.235
方法二:
Math中的round方法
System.out.println((double)Math.round(x*1000)/1000.0); //表示四捨五入保留x小數點後三位小數結果爲1.235
方法三:
DecimalFormat 類
DecimalFormat formatDouble = new DecimalFormat("#.######"); //表示格式化爲保留小數後六位
System.out.println(formatDouble.format(x));//輸出結果爲1.234568