如何在Java中格式化数字?

如何在Java中格式化数字?,java,number-formatting,Java,Number Formatting,如何在Java中格式化数字? 什么是“最佳实践” 在格式化之前,我需要对数字进行四舍五入吗 32.302342343=>32.30 .7323=>0.73 等等。从中,有不同的方法可以做到这一点: 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.s

如何在Java中格式化数字?
什么是“最佳实践”

在格式化之前,我需要对数字进行四舍五入吗

32.302342343
=>
32.30

.7323
=>
0.73

等等。

从中,有不同的方法可以做到这一点:

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



这似乎是最具活力的方式,阅读其他代码时也很容易理解。

您和
String.format()
将成为新的好朋友


使用。

整数,是的。这是最新的

/*
*版权所有(c)1995-2008 Sun Microsystems,Inc.保留所有权利。
*
*以源代码和二进制形式重新分发和使用,带或不带
*如果满足以下条件,则允许进行修改
*满足以下条件:
*
*-源代码的重新分发必须保留上述版权
*请注意,此条件列表和以下免责声明。
*
*-二进制形式的重新分发必须复制上述版权
*请注意,此条件列表和中的以下免责声明
*随分发提供的文件和/或其他材料。
*
*-Sun Microsystems及其子公司的名称
*贡献者可用于支持或推广衍生产品
*未经事先书面许可,不得使用本软件。
*
*本软件由版权所有人和贡献者“作为
*以及任何明示或暗示的保证,包括但不限于:,
*对特定产品的适销性和适用性的默示保证
*目的是否认。在任何情况下,版权所有人或
*出资人对任何直接、间接、附带、特殊、,
*惩戒性或间接损害(包括但不限于,
*替代货物或服务的采购;使用、数据或服务的损失
*利润;或业务中断),无论是何种原因造成的
*责任,无论是合同责任、严格责任还是侵权责任(包括
*因使用本文件而产生的任何疏忽或其他原因)
*软件,即使已告知此类损坏的可能性。
*/ 
导入java.util.*;
导入java.text.*;
公共类DecimalFormatDemo{
静态公共格式(字符串模式,双值){
DecimalFormat myFormatter=新的DecimalFormat(模式);
字符串输出=myFormatter.format(值);
System.out.println(值+“”+图案+“”+输出);
}
静态公共void localizedFormat(字符串模式、双值、Locale loc){
NumberFormat nf=NumberFormat.getNumberInstance(loc);
DecimalFormat df=(DecimalFormat)nf;
df.应用模式(模式);
字符串输出=df.format(值);
System.out.println(pattern+“”+output+“”+loc.toString());
}
静态公共void main(字符串[]args){
自定义格式(“########.###””,123456.789);
自定义格式(“####.##””,123456.789);
自定义格式(“000000.000”,123.78);
自定义格式($####,#########“,12345.67);
自定义格式(“\u00a5########.###”,12345.67);
语言环境currentLocale=新语言环境(“英语”、“美国”);
DecimalFormatSymbols unsualSymbols=新的DecimalFormatSymbols(当前语言环境);
异常符号setDecimalSeparator(“|”);
异常符号。setGroupingSeparator(“^”);
字符串奇怪=“#,###0.###”;
DecimalFormat-weirdFormatter=新的DecimalFormat(奇怪、异常符号);
古怪格式化程序。设置分组大小(4);
stringbizarre=weirdFormatter.format(12345.678);
System.out.println(奇异);
语言环境[]语言环境={
新地区(“欧洲”、“美国”),
新区域设置(“de”、“de”),
新区域设置(“fr”、“fr”)
};
for(int i=0;i
标准库中有两种方法。一种是使用java.text.DecimalFormat。基于java.util.Formatter的其他更神秘的方法(String.format、PrintStream.printf等)应该让C程序员感到高兴(ish)。

请注意,从NumberFormat派生的类(以及大多数其他格式子体)是不同步的。创建格式化对象并将其存储在util类的静态变量中是一种常见(但危险)的做法。在实践中,它将一直工作,直到它开始经历重大负载。

正如Robert在回答中指出的那样:DecimalFormat既不同步,也不能保证线程安全(它可能取决于您使用的JVM版本/供应商)

改用Spring,它是线程安全的。

试试以下方法:

String.format("%.2f", 32.302342342342343);
简单高效

public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}
例如,如果传递到formatDouble()方法中的double值为345.9372,则将 结果是: 345.937 类似地,如果将.7697值传递给该方法,则结果如下:
.770

如果这个答案来自其他人,就不会得到这么多选票
String.format
用于格式化字符串,而不是数字。实际上,String.format类似于C的printf。它可以格式化多种数据类型。当您想将舍入值转换为字符串时,这是一种方法。另一种是使用
DecimalFormat
。而且
DecimalFormat
String.format
稍快。简单的
System.currentTimeMillis
diff揭示了这一点。这仅适用于字符串值这是最好的答案。虽然小数点后的位数完全是特定于域的,但数字需要以区域设置感知的方式显示。String.format()使用正确的数字符号和十进制字符作为默认区域设置。更好的做法是将所需的区域设置作为format()的第一个参数传入,使其显式化
 String.format("%.2f", (double)value);
/*
 * 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]);
        }
     }
 }
String.format("%.2f", 32.302342342342343);
public static void formatDouble(double myDouble){
 NumberFormat numberFormatter = new DecimalFormat("##.000");
 String result = numberFormatter.format(myDouble);
 System.out.println(result);
}