Comment formater un nombre en Java?

Comment formater un nombre en Java?
Quelles sont les “meilleures pratiques”?

Dois-je arrondir un numéro avant de le formater?

32.302342342342343 => 32.30

.7323 => 0.73

etc.

A partir de ce sujet , il existe différentes manières de procéder:

 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 

Le DecimalFormat () semble être le moyen le plus dynamic de le faire, et il est également très facile à comprendre lors de la lecture d’autres codes.

Vous et Ssortingng.format() serez les nouveaux meilleurs amis!

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax

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

Sachez que les classes qui descendent de NumberFormat (et de la plupart des descendants de Format) ne sont pas synchronisées. C’est une pratique courante (mais dangereuse) de créer des objects de format et de les stocker dans des variables statiques dans une classe util. En pratique, cela fonctionnera presque toujours jusqu’à ce qu’il commence à subir une charge importante.

Chiffres ronds, oui. Ceci est la principale source d’exemple .

 /* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redissortingbution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redissortingbutions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redissortingbutions 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 dissortingbution. * * - Neither the name of Sun Microsystems nor the names of its * consortingbutors 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(Ssortingng pattern, double value ) { DecimalFormat myFormatter = new DecimalFormat(pattern); Ssortingng output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output); } static public void localizedFormat(Ssortingng pattern, double value, Locale loc ) { NumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); Ssortingng output = df.format(value); System.out.println(pattern + " " + output + " " + loc.toSsortingng()); } static public void main(Ssortingng[] 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('^'); Ssortingng strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4); Ssortingng 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]); } } } 

Essaye ça:

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

Simple et efficace.

Utilisez DecimalFormat .

Il existe deux approches dans la bibliothèque standard. L’une consiste à utiliser java.text.DecimalFormat. Les autres méthodes plus cryptiques (Ssortingng.format, PrintStream.printf, etc.) basées sur java.util.Formatter devraient satisfaire les programmeurs C (ish).

Comme Robert l’a souligné dans sa réponse: DecimalFormat n’est ni synchronisé, ni l’API garantissant la sécurité des threads (cela peut dépendre de la version / du fournisseur JVM que vous utilisez).

Utilisez plutôt Numberformatter de Spring, qui est thread-safe.

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

Par exemple, si la valeur double passée dans la méthode formatDouble () est 345.9372, le résultat suivant sera le suivant: 345.937 De même, si la valeur .7697 est transmise à la méthode, le résultat suivant sera le suivant: .770