2008-09-08 15 views

Respuesta

106

De this thread, hay diferentes maneras de hacer esto:

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 

El DecimalFormat() parece ser la forma más dinámica para hacerlo, y también es muy fácil de entender cuando se lee el código demás.

+0

Gracias por esta explicación. Sin embargo, Intellij recomienda utilizar 'Double.valueOf' en lugar de' new Double (number) .doubleValue() '. La última línea del último ejemplo sería 'double dd2dec = Double.valueOf (df2.format (dd));' – kumaheiyama

66

¡Usted y String.format() serán nuevos mejores amigos!

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

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

Esta respuesta no habría obtenido tantos upvotes si hubiera venido de otra persona. 'String.format' es para formatear cadenas, no números. –

+3

En realidad, String.format es como el printf de C. Puede formatear varios tipos de tipos de datos. – cesarse

+2

Cuando quiere convertir el valor redondeado como cadena, este es uno de los caminos. Otro está usando 'DecimalFormat'. Y 'DecimalFormat' es ligeramente más rápido que' String.format'. La diferencia simple de 'System.currentTimeMillis' revela eso. – manikanta

11

Números redondos, sí. Este es el main example source.

/* 
* 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]); 
     } 
    } 
} 
4

Hay dos enfoques en la biblioteca estándar. Una es usar java.text.DecimalFormat. Los otros métodos más crípticos (String.format, PrintStream.printf, etc.) basados ​​en java.util.Formatter deben mantener contentos a los programadores de C (ish).

12

Tenga en cuenta que las clases que descienden de NumberFormat (y la mayoría de los demás descendientes de Formato) no están sincronizadas. Es una práctica común (pero peligrosa) crear objetos de formato y almacenarlos en variables estáticas en una clase util. En la práctica, casi siempre funcionará hasta que comience a experimentar una carga significativa.

2

Como Robert ha señalado en su respuesta: DecimalFormat no está sincronizado ni la API garantiza la seguridad del hilo (puede depender de la versión/proveedor de JVM que esté utilizando).

Use Spring's Numberformatter, que es seguro para subprocesos.

8

Prueba esto:

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

simple y eficiente.

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

Por ejemplo, si el valor doble pasa a la formatDouble() método es 345,9372, lo siguiente será ser el resultado: 345.937 mismo modo, si el valor de 0,7697 se pasa al método, la siguiente será el resultado: .770

Cuestiones relacionadas