2009-07-31 27 views
5

Sto utilizzando la classe Java DecimalFormat per stampare numeri in Notazione scientifica. Tuttavia, c'è un problema che ho. Ho bisogno che le stringhe siano di lunghezza fissa indipendentemente dal valore, e il segno sulla potenza di dieci è buttarlo via. Attualmente, questo è ciò che il mio formato assomiglia:Java DecimalFormat Notazione scientifica Domanda

DecimalFormat format = new DecimalFormat("0.0E0"); 

Questo mi dà le seguenti combinazioni: 1.0E1, 1.0E1, -1.0E1, e -1.0E-1.

posso usare setPositivePrefix di ottenere: + 1.0E1, + 1.0E1, -1.0E1 e -1.0E-1, o qualsiasi altra cosa che mi piace, ma non influisce il segno della potenza !

C'è un modo per farlo in modo che io possa avere delle stringhe di lunghezza fisse? Grazie!

Modifica: Ah, quindi non c'è modo di farlo utilizzando l'esistente di Java API? Grazie per i suggerimenti! Penso che potrebbe essere necessario sottoclasse DecimalFormat perché sono limitato dall'interfaccia già installata.

risposta

2

Ecco un modo. Hokey, forse, ma funziona ...

public class DecimalFormatTest extends TestCase { 
    private static class MyFormat extends NumberFormat { 
     private final DecimalFormat decimal; 

     public MyFormat(String pattern) { 
      decimal = new DecimalFormat(pattern); 
     } 

     public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { 
      StringBuffer sb = new StringBuffer(); 
      sb.append(modified(Math.abs(number) > 1.0, decimal.format(number, toAppendTo, pos).toString())); 
      return sb; 
     } 

     private String modified(boolean large, String s) { 
      return large ? s.replace("E", "E+") : s; 
     } 

     public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { 
      StringBuffer sb = new StringBuffer(); 
      sb.append(modified(true, decimal.format(number, toAppendTo, pos).toString())); 
      return sb; 
     } 

     public Number parse(String source, ParsePosition parsePosition) { 
      return decimal.parse(source, parsePosition); 
     } 

     public void setPositivePrefix(String newValue) { 
      decimal.setPositivePrefix(newValue); 
     } 
    } 
    private MyFormat format; 

    protected void setUp() throws Exception { 
     format = new MyFormat("0.0E0"); 
     format.setPositivePrefix("+"); 
    } 

    public void testPositiveLargeNumber() throws Exception { 
     assertEquals("+1.0E+2", format.format(100.0)); 
    } 

    public void testPositiveSmallNumber() throws Exception { 
     assertEquals("+1.0E-2", format.format(0.01)); 
    } 

    public void testNegativeLargeNumber() throws Exception { 
     assertEquals("-1.0E+2", format.format(-100.0)); 
    } 

    public void testNegativeSmallNumber() throws Exception { 
     assertEquals("-1.0E-2", format.format(-0.01)); 
    } 
} 

In alternativa si potrebbe sottoclasse DecimalFormat, ma trovo generalmente più pulito non sottoclasse da classi concrete.

2

Potrebbe utilizzare printf() invece:

Format format = new DecimalFormat("0.0E0"); 
Double d = new Double(.01); 
System.out.println(format.format(d)); 
System.out.printf("%1.1E\n", d); 
d = new Double(100); 
System.out.println(format.format(d)); 
System.out.printf("%1.1E\n", d); 

uscita:

1.0E-2 
1.0E-02 
1.0E2 
1.0E+02 

Se avete bisogno di uscita ad un String, invece, è possibile utilizzare le informazioni fornite al Formatted Printing for Java (sprintf) di farlo.

EDIT: Wow, che PrintfFormat() cosa è enorme e sembra essere inutile:

OutputStream b = new ByteArrayOutputStream(); 
PrintStream p = new PrintStream(b); 
p.printf("%1.1E", d); 
System.out.println(b.toString()); 

ho avuto l'idea per il codice di cui sopra da Get an OutputStream into a String.

4

questo ha funzionato sotto forma di me,

DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.US); 

    if (value > 1 || value < -1) { 
     SYMBOLS.setExponentSeparator("e+"); 
    } else { 
     SYMBOLS.setExponentSeparator("e"); 
    } 

    DecimalFormat format = new DecimalFormat(sb.toString(), SYMBOLS); 
-1

Perché non usare "0.0E + 0" modello, invece? Notare il segno più prima dell'ultimo zero.

+0

Poiché i risultati del modello suggerito in un java.lang.IllegalArgumentException' contenente il testo ': modello esponenziale "0.0E + 0" _Malformed _ –

0

Come utilizzare?
Vedere il metodo formatTest.

if (value.compareTo(positive) == 1 || value.compareTo(negative) == -1) è utile per numeri molto grandi

/** 
* inspired by:<br> 
* https://stackoverflow.com/a/13065493/8356718 
* https://stackoverflow.com/a/18027214/8356718 
* https://stackoverflow.com/a/25794946/8356718 
*/ 
public static String format(String number, int scale) { 
    BigDecimal value = new BigDecimal(number); 
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US); 
    BigDecimal positive = new BigDecimal(1);// scale is zero 
    positive.setScale(0);// unnecessary 
    BigDecimal negative = new BigDecimal(-1);// scale is zero 
    negative.setScale(0);// unnecessary 
    if (value.compareTo(positive) == 1 || value.compareTo(negative) == -1) { 
     symbols.setExponentSeparator("e+"); 
    } else { 
     symbols.setExponentSeparator("e"); 
    } 
    DecimalFormat formatter = new DecimalFormat("0.0E0", symbols); 
    formatter.setRoundingMode(RoundingMode.HALF_UP); 
    formatter.setMinimumFractionDigits(scale); 
    return formatter.format(value); 
} 

/** 
* set the scale automatically 
*/ 
public static String format(String number) { 
    BigDecimal value = new BigDecimal(number); 
    return format(number, value.scale() > 0 ? value.precision() : value.scale()); 
} 

/* 
output: 
---------- 
0e0 
1.0e-2 
-1.0e-2 
1.234560e-5 
-1.234560e-5 
1e0 
-1e0 
3e+0 
-3e+0 
2e+2 
-2e+2 
---------- 
0.0000000000e0 
1.0000000000e-2 
-1.0000000000e-2 
1.2345600000e-5 
-1.2345600000e-5 
1.0000000000e0 
-1.0000000000e0 
3.0000000000e+0 
-3.0000000000e+0 
2.0000000000e+2 
-2.0000000000e+2 
---------- 
*/ 
public static void formatTest() { 
    System.out.println("----------"); 
    System.out.println(format("0")); 
    System.out.println(format("0.01")); 
    System.out.println(format("-0.01")); 
    System.out.println(format("0.000")); 
    System.out.println(format("-0.000")); 
    System.out.println(format("1")); 
    System.out.println(format("-1")); 
    System.out.println(format("3")); 
    System.out.println(format("-3")); 
    System.out.println(format("200")); 
    System.out.println(format("-200")); 
    System.out.println("----------"); 
    System.out.println(format("0", 10)); 
    System.out.println(format("0.01", 10)); 
    System.out.println(format("-0.01", 10)); 
    System.out.println(format("0.000", 10)); 
    System.out.println(format("-0.000", 10)); 
    System.out.println(format("1", 10)); 
    System.out.println(format("-1", 10)); 
    System.out.println(format("3", 10)); 
    System.out.println(format("-3", 10)); 
    System.out.println(format("200", 10)); 
    System.out.println(format("-200", 10)); 
    System.out.println("----------"); 
} 
+0

Si prega di modificare voi pubblicare per includere una spiegazione di come risponde alla domanda. –

Problemi correlati