32.30.7323 => 0.73等等通过此线程,可以有不同的方法来执行此操作:1234567891011double r = 5.1234;
System.o"/>

如何用Java格式化数字?

如何用Java格式化数字?

How do I format a number in Java?

如何用Java格式化数字?
什么是"最佳做法"?

格式化之前是否需要四舍五入一个数字?

32.302342342342343 => 32.30

.7323 => 0.73

等等


通过此线程,可以有不同的方法来执行此操作:

1
2
3
4
5
6
7
8
9
10
11
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
1
f = (float) (Math.round(n*100.0f)/100.0f);
1
2
3
4
5
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

DecimalFormat()似乎是最动态的方法,在阅读其他代码时也很容易理解。


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

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

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


请注意,源自NumberFormat的类(以及大多数其他Format的后代)不会同步。创建格式对象并将其存储在util类的静态变量中是一种常见(但很危险)的做法。在实践中,它几乎总是可以工作,直到开始承受很大的负载。


舍入数字,是的。这是主要的示例来源。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * 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]);
        }
     }
 }

尝试这个:

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

简单高效。


使用DecimalFormat。


标准库中有两种方法。一种是使用java.text.DecimalFormat。基于java.util.Formatter的其他更多隐秘方法(String.format,PrintStream.printf等)应使C程序员满意。


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

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


1
2
3
4
5
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


推荐阅读

    linux远程执行多命令?

    linux远程执行多命令?,工具,服务,命令,状态,暂停,代码,底部,时间,地址,系统,L

    linux周期执行命令?

    linux周期执行命令?,工作,系统,周期,地址,命令,工具,信息,时间,任务,目录,lin

    linux命令执行很慢?

    linux命令执行很慢?,软件,系统,工具,分析,机构,服务,培训,教育,数字,数据,Lin

    linux命令行执行py?

    linux命令行执行py?,系统,环境,官网,一致,文件,程序,脚本,源文件,后台,终端,l

    linux查看执行命令?

    linux查看执行命令?,系统,服务,情况,信息,命令,暂停,标准,概念,实时,第一,lin

    linux命令连续执行?

    linux命令连续执行?,连续,通信,工具,数据,代码,命令,设备,系统,发行,情况,如

    linux执行命令卡住?

    linux执行命令卡住?,系统,环境,密码,数据,信息,分析,软件,异常,服务,命令,Lin

    linux命令执行不动了?

    linux命令执行不动了?,系统,电脑,数据,管理,信息,密码,命令,环境,地方,分析,l

    go操作linux命令?

    go操作linux命令?,系统,工具,环境,软件,标准,网上,最新,信息,设备,电脑,Linux

    linux脚步中执行命令?

    linux脚步中执行命令?,工具,代码,命令,名称,系统,连续,环境,发行,文件,终端,l

    linux命令操作vim?

    linux命令操作vim?,系统,地址,工作,命令,模式,标准,信息,入口,连续,时间,Linu

    linux后台执行命令?

    linux后台执行命令?,暂停,状态,系统,服务,标准,命令,后台,地方,进程,终端,lin

    linux执行权限命令行?

    linux执行权限命令行?,地址,电脑,系统,数字,工作,权限,目录,文件,新增,信息,L

    linux命令的执行时间?

    linux命令的执行时间?,时间,系统,周期,信息,命令,设备,环境,地址,基础,进程,l

    linux快速格式化命令?

    linux快速格式化命令?,电脑,管理,系统,位置,设备,环境,磁盘,命令,终端,硬盘,l

    格式化u盘linux命令?

    格式化u盘linux命令?,系统,电脑,工具,数据,环境,信息,盘后,平台,软件,图片,如

    linux操作不了命令?

    linux操作不了命令?,系统,密码,不了,命令,位置,信息,情况,网络,地址,定期,lin

    linux编程执行命令?

    linux编程执行命令?,电脑,系统,环境,命令,基础,发行,工具,代码,地址,名称,lin

    程序执行linux命令?

    程序执行linux命令?,系统,工作,地址,环境,信息,管理,命令,文件,目录,程序,lin

    linux运维操作命令?

    linux运维操作命令?,系统,网络,基础,标准,工具,信息,工作,命令,软件,数据,lin