Domanda

C'è un modo per utilizzare DecimalFormat (o qualche altro standard di formattazione) per formattare i numeri in questo modo:

  

1.000.000 => 1,00M

     

1.234.567 => 1.23m

     

1.234.567,89 mille => 1234.57M

Fondamentalmente dividendo un numero da 1 milione, mantenendo 2 decimali, e battendosi una 'M' sull'estremità. Ho pensato di creare una nuova sottoclasse di NumberFormat ma sembra più complicato di quanto immaginassi.

Sto scrivendo un'API che ha un metodo formato che assomiglia a questo:

public String format(double value, Unit unit); // Unit is an enum

Internamente, sono la mappatura oggetti Unità a NumberFormatters. L'implementazione è qualcosa di simile:

public String format(double value, Unit unit)
{
    NumberFormatter formatter = formatters.get(unit);
    return formatter.format(value);
}

Si noti che a causa di questo, non posso aspettare il cliente di dividere per 1 milione, e non posso semplicemente usare String.Format () senza avvolgendolo in un NumberFormatter.

È stato utile?

Soluzione

String.format("%.2fM", theNumber/ 1000000.0);

Per ulteriori informazioni consultare la String.Format javadocs .

Altri suggerimenti

Si noti che se si dispone di un BigDecimal, è possibile utilizzare il metodo movePointLeft:

new DecimalFormat("#.00").format(value.movePointLeft(6));

Ecco una sottoclasse di NumberFormat che ho montata su. Sembra che fa il lavoro, ma non sono del tutto sicuro che sia il modo migliore:

private static final NumberFormat MILLIONS = new NumberFormat()
{
    private NumberFormat LOCAL_REAL = new DecimalFormat("#,##0.00M");

    public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos)
    {
        double millions = number / 1000000D;
        if(millions > 0.1) LOCAL_REAL.format(millions, toAppendTo, pos);

        return toAppendTo;
    }

    public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos)
    {
        return format((double) number, toAppendTo, pos);
    }

    public Number parse(String source, ParsePosition parsePosition)
    {
        throw new UnsupportedOperationException("Not implemented...");
    }
};

Perché non semplicemente?

DecimalFormat df = new DecimalFormat("0.00M");
System.out.println(df.format(n / 1000000));

Date un'occhiata a ChoiseFormat .

Un modo più semplice sarebbe quella di utilizzare un wrapper che automaticamente diviso da 1m per voi.

Per il momento, è necessario utilizzare CompactDecimalFormat , che localizzare il risultato formattazione per locali non-inglese. Altri locali potrebbero non utilizzare un suffisso "Milioni".

Questa funzionalità sarà standard Java JDK 12 con CompactNumberFormat.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top