2011-01-19 13 views
12

ho una variabile di tipo double, ho bisogno di stamparlo in fino a 3 decimali di precisione, ma non dovrebbe avere alcun zeri finali ...formattazione virgola mobile Numbers

ad es. Ho bisogno

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

Ho provato ad utilizzare DecimalFormatter, sto facendo di sbagliato?

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

Grazie. :)

risposta

21

provare il modello "0.###" invece di "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)); 
     } 
    } 
} 

uscita:

2.5 
2 
1.375 
2.12 
+0

@ st0le, evviva! –

4

classe NumberFormat Usa.

Esempio:

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

uscita sarà 2,5 e non 2.500.

6

La soluzione è quasi corretta, ma è necessario sostituire gli zero '0' nel modello di formato decimale con hash "#".

Così dovrebbe apparire come questo:

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

E quella linea non è necesary (come decimalSeparatorAlwaysShown è false per impostazione predefinita):

myFormatter.setDecimalSeparatorAlwaysShown(false); 

Ecco breve riassunto da javadocs:

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

E il collegamento a javadoc: DecimalFormat

+0

+1 per le informazioni aggiuntive. – st0le

+0

Come stampare il numero in virgola mobile poiché è 220.90? –