如何在Java中格式化数字?

ScA*_*er2 109 java number-formatting

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

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

32.302342342342343 => 32.30

.7323 => 0.73

等等

Esp*_*spo 120

这个线程,有不同的方法来做到这一点:

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
Run Code Online (Sandbox Code Playgroud)
f = (float) (Math.round(n*100.0f)/100.0f);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

DecimalFormat的()似乎是这样做的最有活力的方式,并且它也很容易阅读别人的代码时,理解.


Jef*_*ood 74

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

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

 String.format("%.2f", (double)value);
Run Code Online (Sandbox Code Playgroud)

  • 如果来自其他任何人,这个答案就不会有这么多的赞成.`String.format`用于格式化字符串,而不是数字. (26认同)
  • 实际上,String.format就像C的printf.它可以格式化几种数据类型. (4认同)
  • 如果要将舍入值转换为字符串,这是其中一种方法.其他的是使用`DecimalFormat`.并且`DecimalFormat`比`String.format`略快.简单的`System.currentTimeMillis`差异揭示了这一点. (3认同)

Rob*_*ker 14

请注意,从NumberFormat(以及大多数其他Format后代)下降的类不会同步.创建格式对象并将它们存储在util类中的静态变量中是一种常见(但危险)的做法.在实践中,它几乎总是有效,直到它开始经历重大负载.


Vin*_*vic 11

回合数,是的.这是主要的示例源.

/*
 * 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]);
        }
     }
 }
Run Code Online (Sandbox Code Playgroud)


Nau*_*lus 8

试试这个:

String.format("%.2f", 32.302342342342343);
Run Code Online (Sandbox Code Playgroud)

简单高效.