Wie formatiere ich eine Zahl in Java?


114

Wie formatiere ich eine Zahl in Java?
Was sind die "Best Practices"?

Muss ich eine Zahl runden, bevor ich sie formatiere?

32.302342342342343 => 32.30

.7323 => 0.73

etc.

Antworten:


124

In diesem Thread gibt es verschiedene Möglichkeiten, dies zu tun:

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

Das DecimalFormat () scheint die dynamischste Methode zu sein, und es ist auch sehr einfach zu verstehen, wenn Sie anderen Code lesen.


Danke für diese Erklärung. Intellij empfiehlt jedoch, Double.valueOfanstelle von zu verwenden new Double(number).doubleValue(). Die letzte Zeile des letzten Beispiels wäre daherdouble dd2dec = Double.valueOf(df2.format(dd));
kumaheiyama

Das DecimalFormat-Muster in dieser Antwort ist gut für die USA, aber in den meisten anderen Regionen der Welt falsch. Das Gruppierungszeichen (Komma in den USA, aber Leerzeichen oder Punkt in anderen Gebietsschemas), die Gruppierungsgröße (drei in den USA und den meisten Gebietsschemas, jedoch in Indien unterschiedlich), das Dezimalzeichen (Punkt in den USA, aber Komma in anderen Gebietsschemas) . Der richtige Weg, um eine DecimalFormat-Instanz zu erhalten, ist: DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance (Gebietsschema)
vonWippersnap

74

Sie und String.format()werden neue beste Freunde sein!

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

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

29
Diese Antwort hätte nicht so viele positive Stimmen bekommen, wenn sie von jemand anderem gekommen wäre. String.formatdient zum Formatieren von Zeichenfolgen, nicht von Zahlen.
Dónal

4
Eigentlich ist String.format wie Cs printf. Es können verschiedene Arten von Datentypen formatiert werden.
Kaiserschnitt

3
Wenn Sie den gerundeten Wert als Zeichenfolge konvertieren möchten, ist dies eine der Möglichkeiten. Andere verwenden DecimalFormat. Und DecimalFormatist etwas schneller als String.format. Simple System.currentTimeMillisDiff zeigt das.
Manikanta

Dies nur für String-Wert
T8Z

Dies ist die beste Antwort. Während die Anzahl der Stellen nach dem Dezimalpunkt vollständig domänenspezifisch ist, müssen die Zahlen länderspezifisch angezeigt werden. String.format () verwendet die richtigen Zahlensymbole und Dezimalzeichen für das Standardgebietsschema. Noch besser wäre es, das erforderliche Gebietsschema als ersten Parameter an format () zu übergeben, um es explizit zu machen.
vonWippersnap

14

Beachten Sie, dass Klassen, die von NumberFormat (und den meisten anderen Format-Nachkommen) abstammen, nicht synchronisiert werden. Es ist eine gängige (aber gefährliche) Praxis, Formatobjekte zu erstellen und in statischen Variablen in einer util-Klasse zu speichern. In der Praxis funktioniert es so gut wie immer, bis eine erhebliche Belastung auftritt.


1
Danke dir! Du hast mich gerade gerettet.
David Thielen

11

Runde Zahlen, ja. Dies ist die Hauptbeispielquelle .

/*
 * 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

Versuche dies:

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

Einfach und effizient.



4

In der Standardbibliothek gibt es zwei Ansätze. Eine ist die Verwendung von java.text.DecimalFormat. Die anderen kryptischeren Methoden (String.format, PrintStream.printf usw.), die auf java.util.Formatter basieren, sollten C-Programmierer bei Laune halten (ish).


2

Wie Robert in seiner Antwort ausgeführt hat: DecimalFormat ist weder synchronisiert noch garantiert die API die Thread-Sicherheit (dies kann von der von Ihnen verwendeten JVM-Version / dem verwendeten JVM-Anbieter abhängen).

Verwenden Sie stattdessen Spring's Numberformatter , der threadsicher ist.


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

Wenn beispielsweise der an die formatDouble () -Methode übergebene Doppelwert 345.9372 ist, ist das folgende Ergebnis: 345.937 Wenn der Wert .7697 an die Methode übergeben wird, ist das Folgende das Ergebnis: .770

Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.