Come formatto un numero in Java?


114

Come formatto un numero in Java?
Quali sono le "migliori pratiche"?

Dovrò arrotondare un numero prima di formattarlo?

32.302342342342343 => 32.30

.7323 => 0.73

eccetera.

Risposte:


124

Da questo thread , ci sono diversi modi per farlo:

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

Il DecimalFormat () sembra essere il modo più dinamico per farlo, ed è anche molto facile da capire quando si legge il codice altrui.


Grazie per questa spiegazione. Tuttavia, Intellij consiglia di utilizzare al Double.valueOfposto di new Double(number).doubleValue(). L'ultima riga dell'ultimo esempio sarebbe quindidouble dd2dec = Double.valueOf(df2.format(dd));
kumaheiyama

Il modello DecimalFormat in questa risposta è ottimo per gli Stati Uniti, ma sbagliato nella maggior parte delle altre impostazioni locali del mondo. Il carattere di raggruppamento (virgola negli Stati Uniti, ma spazio o punto in altre lingue), la dimensione del raggruppamento (tre negli Stati Uniti e nella maggior parte delle lingue, ma diverso in India), il carattere decimale (punto negli Stati Uniti, ma virgola in altre lingue) . Il modo corretto per ottenere un'istanza DecimalFormat è: DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance (locale)
vonWippersnap

74

Tu e String.format()sarai nuovi migliori amici!

https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

 String.format("%.2f", (double)value);

29
Questa risposta non avrebbe avuto così tanti voti positivi se fosse arrivata da qualcun altro. String.formatserve per formattare le stringhe, non i numeri.
Dónal

4
In realtà, String.format è come printf di C. Può formattare diversi tipi di dati.
Cesarse

3
Quando vuoi convertire il valore arrotondato come stringa, questo è uno dei modi. Altro sta usando DecimalFormat. Ed DecimalFormatè leggermente più veloce di String.format. Un semplice System.currentTimeMillisdiff lo rivela.
manikanta

Questo solo per il valore di stringa
T8Z

Questa è la migliore risposta. Sebbene il numero di cifre dopo la virgola decimale sia completamente specifico del dominio, i numeri devono essere visualizzati in modo consapevole delle impostazioni locali. String.format () utilizza i simboli numerici corretti e il carattere decimale per la locale predefinita. Ancora meglio sarebbe passare la locale richiesta come primo parametro a format () per renderla esplicita.
vonWippersnap

14

Tieni presente che le classi che discendono da NumberFormat (e la maggior parte degli altri discendenti di Format) non sono sincronizzate. È una pratica comune (ma pericolosa) creare oggetti formato e memorizzarli in variabili statiche in una classe util. In pratica, funzionerà praticamente sempre fino a quando non inizierà a subire un carico significativo.


1
Grazie! Mi hai appena salvato.
David Thielen

11

Numeri tondi, sì. Questa è la principale fonte di esempio .

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 


import java.util.*;
import java.text.*;

public class DecimalFormatDemo {

    static public void customFormat(String pattern, double value ) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        System.out.println(value + "  " + pattern + "  " + output);
    }

    static public void localizedFormat(String pattern, double value,                                       Locale loc ) {
        NumberFormat nf = NumberFormat.getNumberInstance(loc);
        DecimalFormat df = (DecimalFormat)nf;
        df.applyPattern(pattern);
        String output = df.format(value);
        System.out.println(pattern + "  " + output + "  " + loc.toString());
    }

    static public void main(String[] args) {

        customFormat("###,###.###", 123456.789);
        customFormat("###.##", 123456.789);
        customFormat("000000.000", 123.78);
        customFormat("$###,###.###", 12345.67);
        customFormat("\u00a5###,###.###", 12345.67);

        Locale currentLocale = new Locale("en", "US");

        DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
        unusualSymbols.setDecimalSeparator('|');
        unusualSymbols.setGroupingSeparator('^');
        String strange = "#,##0.###";
        DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
        weirdFormatter.setGroupingSize(4);
        String bizarre = weirdFormatter.format(12345.678);
        System.out.println(bizarre);

        Locale[] locales = {
            new Locale("en", "US"),
            new Locale("de", "DE"),
            new Locale("fr", "FR")
        };

        for (int i = 0; i < locales.length; i++) {
            localizedFormat("###,###.###", 123456.789, locales[i]);
        }
     }
 }

8

Prova questo:

String.format("%.2f", 32.302342342342343);

Semplice ed efficiente.



4

Esistono due approcci nella libreria standard. Uno è usare java.text.DecimalFormat. Gli altri metodi più criptici (String.format, PrintStream.printf, ecc.) Basati su java.util.Formatter dovrebbero rendere felici i programmatori C (ish).


2

Come ha sottolineato Robert nella sua risposta: DecimalFormat non è sincronizzato né l'API garantisce la sicurezza dei thread (potrebbe dipendere dalla versione / fornitore di JVM che stai utilizzando).

Usa invece il Numberformatter di Spring , che è thread-safe.


2
public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}

Ad esempio, se il valore double passato al metodo formatDouble () è 345.9372, il risultato sarà il seguente: 345.937 Allo stesso modo, se il valore .7697 viene passato al metodo, il risultato sarà il seguente: .770

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.