【问题标题】:How do I format a number in Java?如何在 Java 中格式化数字?
【发布时间】:2010-09-08 05:02:01
【问题描述】:

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

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

32.302342342342343 => 32.30

.7323 => 0.73

等等

【问题讨论】:

    标签: java number-formatting


    【解决方案1】:

    来自this thread,有不同的方法可以做到这一点:

    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
    

    DecimalFormat() 好像是最动态的方式,看别人的代码也很容易理解。

    【讨论】:

    • 感谢您的解释。但是,Intellij 建议使用 Double.valueOf 而不是 new Double(number).doubleValue()。因此,最后一个示例的最后一行将是 double dd2dec = Double.valueOf(df2.format(dd));
    • 这个答案中的 DecimalFormat 模式对美国来说很好,但在世界上大多数其他地区都是错误的。分组字符(在美国是逗号,但在其他语言环境中是空格或点),分组大小(在美国和大多数语言环境中是三个,但在印度不同),小数字符(在美国是点,但在其他语言环境中是逗号) .获取 DecimalFormat 实例的正确方法是: DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(locale)
    【解决方案2】:

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

    https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

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

    【讨论】:

    • 这个答案如果来自其他人,就不会得到这么多的赞成票。 String.format 用于格式化字符串,而不是数字。
    • 其实String.format就像C的printf。它可以格式化多种数据类型。
    • 当您想将四舍五入的值转换为字符串时,这是一种方法。其他正在使用DecimalFormat。并且DecimalFormatString.format 稍快。简单的System.currentTimeMillis diff 揭示了这一点。
    • 这仅适用于字符串值
    • 这是最好的答案。虽然小数点后的位数完全是特定于域的,但数字需要以区域设置感知的方式显示。 String.format() 使用正确的数字符号和十进制字符作为默认语言环境。更好的办法是将所需的语言环境作为第一个参数传递给 format() 以使其明确。
    【解决方案3】:

    使用DecimalFormat

    【讨论】:

      【解决方案4】:

      整数,是的。这是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]);
              }
           }
       }
      

      【讨论】:

        【解决方案5】:

        标准库中有两种方法。一种是使用 java.text.DecimalFormat。基于 java.util.Formatter 的其他更神秘的方法(String.format、PrintStream.printf 等)应该让 C 程序员高兴(ish)。

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

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

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

            【讨论】:

              【解决方案8】:

              试试这个:

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

              简单高效。

              【讨论】:

                【解决方案9】:
                public static void formatDouble(double myDouble){
                 NumberFormat numberFormatter = new DecimalFormat("##.000");
                 String result = numberFormatter.format(myDouble);
                 System.out.println(result);
                }
                

                例如,如果传递给 formatDouble() 方法的双精度值是 345.9372,则以下将 结果: 345.937 同样,如果将值 .7697 传递给方法,则结果如下: .770

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2011-09-19
                  • 2014-04-27
                  • 1970-01-01
                  • 2017-11-16
                  • 2015-07-22
                  • 1970-01-01
                  相关资源
                  最近更新 更多