2011-01-19 82 views
12

double類型的變量,我需要打印在高達的精度3位小數,但它不應該有任何尾隨零...格式化浮點數

如。我需要

2.5 // not 2.500 
2 // not 2.000 
1.375 // exactly till 3 decimals 
2.12 // not 2.120 

我試過使用DecimalFormatter,我做錯了嗎?

DecimalFormat myFormatter = new DecimalFormat("0.000"); 
myFormatter.setDecimalSeparatorAlwaysShown(false); 

謝謝。 :)

回答

21

嘗試模式"0.###"而不是"0.000"

import java.text.DecimalFormat; 

public class Main { 
    public static void main(String[] args) { 
     DecimalFormat df = new DecimalFormat("0.###"); 
     double[] tests = {2.50, 2.0, 1.3751212, 2.1200}; 
     for(double d : tests) { 
      System.out.println(df.format(d)); 
     } 
    } 
} 

輸出:

2.5 
2 
1.375 
2.12 
+0

@ st0le,歡呼! – 2011-01-19 08:35:56

4

使用NumberFormat類。

實施例:

double d = 2.5; 
    NumberFormat n = NumberFormat.getInstance(); 
    n.setMaximumFractionDigits(3); 
    System.out.println(n.format(d)); 

輸出將是2.5,而不是2.500。

6

您的解決方案几乎是正確的,但您應該用散列「#」替換零值格式的零「0」。

因此,它應該是這樣的:

DecimalFormat myFormatter = new DecimalFormat("#.###"); 

這行不necesary(如decimalSeparatorAlwaysShownfalse默認):

myFormatter.setDecimalSeparatorAlwaysShown(false); 

下面是從的javadoc簡短的摘要:

Symbol Location Localized? Meaning 
0 Number Yes Digit 
# Number Yes Digit, zero shows as absent 

並鏈接到javadoc:DecimalFormat

+0

+1爲額外的信息。 – st0le 2011-01-19 09:25:03