2016-07-17 36 views
1

我只需要在與零不同時顯示浮點值的小數位。如果不爲零,則格式float顯示小數位數java

  1. 5.0應顯示爲。
  2. 7.3應顯示爲7.3
  3. 9.000003應顯示爲9.000003

如何使用正則表達式或DecimalFormat以這種方式進行格式化?

+0

檢查[這](http://stackoverflow.com/a/12045199/4101906) –

回答

1

要顯示小數你的願望,使用下面的代碼片段的方式:

// This is to show symbol . instead of , 
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US); 
// Define the maximum number of decimals (number of symbols #) 
DecimalFormat df = new DecimalFormat("#.##########", otherSymbols); 

// type: double 
System.out.println(df.format(5.0)); // writes 5 
System.out.println(df.format(7.3)); // writes 7.3 
System.out.println(df.format(9.000003)); // writes 9.000003 

// type: float 
System.out.println(df.format(9.000003f)); // writes 9.000002861 
+0

它的作品! Thaks! –

相關問題