C和Java中如何控制浮點數的精度輸出
阿新 • • 發佈:2019-02-19
1、C語言中可以通過輸出格式說明符來控制浮點數的輸出,如:%2.3f,整數位置的2表示整數部分固定以2位寬度輸出,如果資料的位數小於2(且禁止輸出小數的情況下,即%2.0f),則左端補以空格,否則按實際位數輸出;若大於2,則按實際位數輸出。小數位置的3表示輸出精確到小數點後3位,如果實際小數不足3位,則在末尾補0,若大於3位,則按四捨五入取前3位。
程式碼如下:
執行結果:#include <stdio.h> #include <stdlib.h> #define PI 3.1415926 #define a 314.15 int main() { printf("%2.0f\n", PI); printf("%2.3f\n", PI); printf("%2.3f\n", a); return 0; }
2、Java中通常使用String.format()四捨五入控制精度輸出,查API文件可知:
public static String format(String format, Object... args)
Returns a formatted string using the specified formatstring and arguments.
即String.format()會返回一個將引數args使用特定的格式格式化後的字串。
程式碼如下:
執行結果:public class Test { public static void main(String args[]) { System.out.println(Math.PI); System.out.println(String.format("%.3f", Math.PI)); } }
同樣也可以使用java.text.DecimalFormat進行四捨五入規則化,public DecimalFormat(String pattern)
程式碼如下:
執行結果:import java.text.DecimalFormat; public class Test { public static void main(String args[]) { DecimalFormat df1 = new DecimalFormat("#.000"); DecimalFormat df2 = new DecimalFormat("0.000"); System.out.println(df1.format(0.123456)); // double型引數 System.out.println(df2.format(0.123456)); } }
用#和0的唯一區別是0在數位不足時會自動補足,注意:0和#不能同時出現在小數點的同一側。