Domanda

C'è un modo per formattare un numero decimale come segue:

100   -> "100"  
100.1 -> "100.10"

Se è un numero tondo, omettere la parte decimale. formattare In caso contrario, con due cifre decimali.

È stato utile?

Soluzione

ne dubito. Il problema è che il 100 non è mai 100 se si tratta di un galleggiante, è normalmente 99.9999999999 o 100,0000,001 mila o qualcosa del genere.

Se si vuole formattare in questo modo, è necessario definire un Epsilon, che è, una distanza massima da un numero intero, e l'uso intero formattazione se la differenza è più piccolo, e un galleggiante altrimenti.

Qualcosa di simile a questo sarebbe fare il trucco:

public String formatDecimal(float number) {
  float epsilon = 0.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}

Altri suggerimenti

Mi consiglia di utilizzare il pacchetto java.text:

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

Questo ha il vantaggio di essere locale specifica.

Ma, se è necessario, troncare la stringa che si ottiene indietro se si tratta di un dollaro intero:

if (moneyString.endsWith(".00")) {
    int centsIndex = moneyString.lastIndexOf(".00");
    if (centsIndex != -1) {
        moneyString = moneyString.substring(1, centsIndex);
    }
}
double amount =200.0;
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(currencyFormatter.format(amount));

o

double amount =200.0;
System.out.println(NumberFormat.getCurrencyInstance(new Locale("en", "US"))
        .format(amount));
  

Il modo migliore per la valuta di visualizzazione

Output

  

$ 200,00

Se non si desidera utilizzare l'uso segno questo metodo

double amount = 200;
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println(twoPlaces.format(amount));
  

200.00

     

Anche questo può essere l'uso (con il separatore delle migliaia)

double amount = 2000000;    
System.out.println(String.format("%,.2f", amount));          
  

2.000.000,00

Non ho trovato alcuna soluzione buona dopo google search, basta inviare la mia soluzione per altro per riferimento. uso priceToString in formato denaro.

public static String priceWithDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.00");
    return formatter.format(price);
}

public static String priceWithoutDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.##");
    return formatter.format(price);
}

public static String priceToString(Double price) {
    String toShow = priceWithoutDecimal(price);
    if (toShow.indexOf(".") > 0) {
        return priceWithDecimal(price);
    } else {
        return priceWithoutDecimal(price);
    }
}

Sì. È possibile utilizzare java.util.Formatter . È possibile utilizzare una stringa di formattazione come "% 10.2f"

Sto usando questo (usando StringUtils da commons-lang):

Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");

Si deve solo prendere cura del locale e della corda corrispondente a tagliare.

Credo che questo sia semplice e chiaro per la stampa di una valuta:

DecimalFormat df = new DecimalFormat("$###,###.##"); // or pattern "###,###.##$"
System.out.println(df.format(12345.678));

uscita: $ 12,345.68

E una delle possibili soluzioni per la domanda:

public static void twoDecimalsOrOmit(double d) {
    System.out.println(new DecimalFormat(d%1 == 0 ? "###.##" : "###.00").format(d));
}

twoDecimalsOrOmit((double) 100);
twoDecimalsOrOmit(100.1);

Output:

100

100.10

Noi di solito bisogno di fare l'inverso, se il campo di denaro JSON è un galleggiante, può venire come 3.1, 3.15 o semplicemente 3.

In questo caso potrebbe essere necessario arrotondare per la visualizzazione corretta (e per essere in grado di utilizzare una maschera su un campo in seguito):

floatvalue = 200.0; // it may be 200, 200.3 or 200.37, BigDecimal will take care
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);

BigDecimal valueAsBD = BigDecimal.valueOf(value);
    valueAsBD.setScale(2, BigDecimal.ROUND_HALF_UP); // add digits to match .00 pattern

System.out.println(currencyFormatter.format(amount));

si dovrebbe fare qualcosa di simile:

public static void main(String[] args) {
    double d1 = 100d;
    double d2 = 100.1d;
    print(d1);
    print(d2);
}

private static void print(double d) {
    String s = null;
    if (Math.round(d) != d) {
        s = String.format("%.2f", d);
    } else {
        s = String.format("%.0f", d);
    }
    System.out.println(s);
}

che stampa:

100

100,10

So che questa è una vecchia questione, ma ...

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}

Si può solo fare qualcosa di simile e passare il numero intero e poi i centesimi dopo.

String.format("$%,d.%02d",wholeNum,change);

Sono d'accordo con @duffymo che è necessario utilizzare i metodi java.text.NumberFormat per questo genere di cose. Si può effettivamente fare tutta la formattazione in modo nativo in esso senza fare alcuna String confronta te stesso:

private String formatPrice(final double priceAsDouble) 
{
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    if (Math.round(priceAsDouble * 100) % 100 == 0) {
        formatter.setMaximumFractionDigits(0);
    }
    return formatter.format(priceAsDouble);
}

bit Coppia di sottolineare:

  • L'intera Math.round(priceAsDouble * 100) % 100 è solo lavorando intorno alle imprecisioni di doppie / carri. In pratica basta controllare se arrotondiamo al luogo centinaia (forse questo è un pregiudizio Stati Uniti) sono lì centesimi rimanenti.
  • Il trucco per rimuovere i decimali è il metodo setMaximumFractionDigits()

Qualunque sia la vostra logica per determinare se i decimali dovrebbero avere troncato, setMaximumFractionDigits() dovrebbe abituarsi.

questo modo migliore per farlo.

    public static String formatCurrency(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

100 -> "100.00"
100.1 -> "100.10"

Se si vuole lavorare su valute, è necessario utilizzare la classe BigDecimal. Il problema è che non c'è modo per memorizzare alcuni numeri float in memoria (ad es. È possibile memorizzare 5,3456, ma non 5,3455), che possono effetti nel calcolo cattivi.

C'è un articolo bello come cooperare con BigDecimal e valute:

http://www.javaworld.com/ JavaWorld / JW-06-2001 / JW-0601-cents.html

Formato 1.000.000,2-1 000 000,20

private static final DecimalFormat DF = new DecimalFormat();

public static String toCurrency(Double d) {
    if (d == null || "".equals(d) || "NaN".equals(d)) {
        return " - ";
    }
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
    DecimalFormatSymbols symbols = DF.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    String ret = DF.format(bd) + "";
    if (ret.indexOf(",") == -1) {
        ret += ",00";
    }
    if (ret.split(",")[1].length() != 2) {
        ret += "0";
    }
    return ret;
}

Questo post in realtà mi ha aiutato a ottenere finalmente quello che voglio. Così ho voluto solo contribuire il mio codice qui per aiutare gli altri. Qui è il mio codice con qualche spiegazione.

Il seguente codice:

double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));

Tornerà:

€ 5,-
€ 5,50
Metodo

Il jeroensFormat reale ():

public String jeroensFormat(double money)//Wants to receive value of type double
{
        NumberFormat dutchFormat = NumberFormat.getCurrencyInstance();
        money = money;
        String twoDecimals = dutchFormat.format(money); //Format to string
        if(tweeDecimalen.matches(".*[.]...[,]00$")){
            String zeroDecimals = twoDecimals.substring(0, twoDecimals.length() -3);
                return zeroDecimals;
        }
        if(twoDecimals.endsWith(",00")){
            String zeroDecimals = String.format("€ %.0f,-", money);
            return zeroDecimals; //Return with ,00 replaced to ,-
        }
        else{ //If endsWith != ,00 the actual twoDecimals string can be returned
            return twoDecimals;
        }
}

Il metodo displayJeroensFormat che chiama il metodo jeroensFormat ()

    public void displayJeroensFormat()//@parameter double:
    {
        System.out.println(jeroensFormat(10.5)); //Example for two decimals
        System.out.println(jeroensFormat(10.95)); //Example for two decimals
        System.out.println(jeroensFormat(10.00)); //Example for zero decimals
        System.out.println(jeroensFormat(100.000)); //Example for zero decimals
    }

avrà il seguente output:

€ 10,50
€ 10,95
€ 10,-
€ 100.000 (In Holland numbers bigger than € 999,- and wit no decimals don't have ,-)

Questo codice utilizza la valuta corrente. Nel mio caso questo è l'Olanda così la stringa formattata per me sarà diverso rispetto per qualcuno negli Stati Uniti.

  • Olanda: 999.999,99
  • USA: 999.999,99

Basta guardare gli ultimi 3 caratteri di quei numeri. Il mio codice ha un'istruzione if per verificare se gli ultimi 3 caratteri sono uguali a", 00" . Per utilizzare questa negli Stati Uniti potrebbe essere necessario cambiamento che a" .00" , se non funziona già.

Sono stato abbastanza pazzo da scrivere la mia propria funzione:

Questo convertirà intero in formato di valuta (può essere modificato per decimali pure):

 String getCurrencyFormat(int v){
        String toReturn = "";
        String s =  String.valueOf(v);
        int length = s.length();
        for(int i = length; i >0 ; --i){
            toReturn += s.charAt(i - 1);
            if((i - length - 1) % 3 == 0 && i != 1) toReturn += ',';
        }
        return "$" + new StringBuilder(toReturn).reverse().toString();
    }
  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }

Questo è quello che ho fatto, utilizzando un numero intero per rappresentare l'importo come centesimi invece:

public static String format(int moneyInCents) {
    String format;
    Number value;
    if (moneyInCents % 100 == 0) {
        format = "%d";
        value = moneyInCents / 100;
    } else {
        format = "%.2f";
        value = moneyInCents / 100.0;
    }
    return String.format(Locale.US, format, value);
}

Il problema con NumberFormat.getCurrencyInstance() è che a volte si vuole veramente $ 20 a essere $ 20, appena sembra meglio di $ 20,00.

Se qualcuno trova il modo migliore di fare questo, utilizzando NumberFormat, sono tutto orecchie.

Per le persone che vuole formattare la valuta, ma non si vuole che sia basata su locali, siamo in grado di fare questo:

val numberFormat = NumberFormat.getCurrencyInstance() // Default local currency
val currency = Currency.getInstance("USD")            // This make the format not locale specific 
numberFormat.setCurrency(currency)

...use the formator as you want...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top