筆試時候,遇到讓你寫輸出小數點后幾位,當時很是頭疼,下來后,查了查發現,沒什么難的。網上有各種情況都討論了(一般分為4種),在這里我着重討論一下比較實用,比較簡單,比較方便操作的幾種:
1 public class DotTest { 2 public static void main(String[] args) { 3 DecimalFormat df = new DecimalFormat("#.000"); 4 double d1 = 12.123456789; 5 6 System.out.println(df.format(d1)); 7 System.out.printf("%.3f",d1); 8 System.out.println();//為了分行顯示 9 System.out.println(String.format("%.3f", d1));//輸出的是字符串 10 } 11 }
輸出結果是:
12.123 12.123 12.123
有人會說第二種 System.out.printf("%.3f",d1);不是標准輸出啊,我想說的是,在這里雖然是c中的輸出形式,但是最起碼它能實現小數位的約束,總比實現不了強得多吧。
所以綜上,我推薦:
- 輸出是數字的話:使用DecimalFormat 類
- 輸出是字符串的話:使用String.format("%.3f", d1);
Over...
參考:
1. https://blog.csdn.net/shiyong1949/article/details/52641152