【问题标题】:How to nicely format floating numbers to string without unnecessary decimal 0's如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串
【发布时间】:2014-01-22 12:57:03
【问题描述】:

64 位双精度可以精确表示整数 +/- 253

鉴于这一事实,我选择使用双精度类型作为我所有类型的单一类型,因为我的最大整数是无符号 32 位数字。

但现在我必须打印这些伪整数,但问题是它们也与实际的双精度数混合在一起。

那么如何在 Java 中很好地打印这些双精度数呢?

我已经尝试过String.format("%f", value),它很接近,除了我得到很多小值的尾随零。

这是%f的示例输出

232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000

我想要的是:

232 0.18 1237875192 4.58 0 1.2345

当然,我可以编写一个函数来修剪这些零,但是由于字符串操作,这会导致很多性能损失。我可以用其他格式的代码做得更好吗?


Tom E. 和 Jeremy S. 的答案是不可接受的,因为他们都任意四舍五入到小数点后两位。请先理解问题再回答。


请注意,String.format(format, args...)取决于区域设置(请参阅下面的答案)。

【问题讨论】:

  • 如果你想要的只是整数,为什么不使用long呢?您会在 2^63-1 时获得更多效果,没有尴尬的格式,并且性能更好。
  • 因为有些值实际上是双精度数
  • 出现此问题的某些情况是 JDK 7 中修复的错误:stackoverflow.com/questions/7564525/…
  • 仅仅是我还是 JavaScript 在数字到字符串的转换方面比 Java 好 100%?
  • System.out.println("YOUR STRING" + YOUR_DOUBLE_VARIABLE);

标签: java string floating-point format double


【解决方案1】:

考虑到语言环境的简单解决方案:

double d = 123.45;
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMANY);
System.out.println(numberFormat.format(d));

由于在德国使用逗号作为小数分隔符,所以上面会打印:

123,45

【讨论】:

    【解决方案2】:
    if (d == Math.floor(d)) {
        return String.format("%.0f", d); //Format is: 0 places after decimal point
    } else {
        return Double.toString(d);
    }
    

    更多信息:https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

    【讨论】:

    • 解释一下。
    • 很好的答案,它不需要解释,因为它自己做。
    • 已添加说明。我希望这至少应该得到 2 次赞成票 ;-)
    【解决方案3】:

    我在我们的JSF 应用程序中使用它来格式化没有尾随零的数字。原始的内置格式化程序要求您指定最大小数位数,这在您有太多小数位数的情况下也很有用。

    /**
     * Formats the given Number as with as many fractional digits as precision
     * available.<br>
     * This is a convenient method in case all fractional digits shall be
     * rendered and no custom format / pattern needs to be provided.<br>
     * <br>
     * This serves as a workaround for {@link NumberFormat#getNumberInstance()}
     * which by default only renders up to three fractional digits.
     *
     * @param number
     * @param locale
     * @param groupingUsed <code>true</code> if grouping shall be used
     *
     * @return
     */
    public static String formatNumberFraction(final Number number, final Locale locale, final boolean groupingUsed)
    {
        if (number == null)
            return null;
    
        final BigDecimal bDNumber = MathUtils.getBigDecimal(number);
    
        final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
        numberFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale()));
        numberFormat.setGroupingUsed(groupingUsed);
    
        // Convert back for locale percent formatter
        return numberFormat.format(bDNumber);
    }
    
    /**
     * Formats the given Number as percent with as many fractional digits as
     * precision available.<br>
     * This is a convenient method in case all fractional digits shall be
     * rendered and no custom format / pattern needs to be provided.<br>
     * <br>
     * This serves as a workaround for {@link NumberFormat#getPercentInstance()}
     * which does not renders fractional digits.
     *
     * @param number Number in range of [0-1]
     * @param locale
     *
     * @return
     */
    public static String formatPercentFraction(final Number number, final Locale locale)
    {
        if (number == null)
            return null;
    
        final BigDecimal bDNumber = MathUtils.getBigDecimal(number).multiply(new BigDecimal(100));
    
        final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
        percentScaleFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale() - 2));
    
        final BigDecimal bDNumberPercent = bDNumber.multiply(new BigDecimal(0.01));
    
        // Convert back for locale percent formatter
        final String strPercent = percentScaleFormat.format(bDNumberPercent);
    
        return strPercent;
    }
    

    【讨论】:

      【解决方案4】:
      float price = 4.30;
      DecimalFormat format = new DecimalFormat("0.##"); // Choose the number of decimal places to work with in case they are different than zero and zero value will be removed
      format.setRoundingMode(RoundingMode.DOWN); // Choose your Rounding Mode
      System.out.println(format.format(price));
      

      这是一些测试的结果:

      4.30     => 4.3
      4.39     => 4.39  // Choose format.setRoundingMode(RoundingMode.UP) to get 4.4
      4.000000 => 4
      4        => 4
      

      【讨论】:

      • 1.23450000呢?
      • 1.23450000 => 1.23
      • 唯一让我满意的解决方案
      • DecimalFormat 不是线程安全的。使用时一定要小心。
      【解决方案5】:

      对于 Kotlin,您可以使用如下扩展:

      fun Double.toPrettyString() =
          if(this - this.toLong() == 0.0)
              String.format("%d", this.toLong())
          else
              String.format("%s", this)
      

      【讨论】:

        【解决方案6】:

        使用分组、舍入和没有不必要的零(双精度)格式化价格。

        规则:

        1. 末尾没有零 (2.0000 = 2; 1.0100000 = 1.01)
        2. 一个点后最多两位数 (2.010 = 2.01; 0.20 = 0.2)
        3. 点后第二位数字后舍入 (1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -&gt; 0)
        4. 返回0 (null/-0 = 0)
        5. 添加$ (= $56/-$56)
        6. 分组 (101101.02 = $101,101.02)

        更多示例:

        -99.985 = -$99.99

        10 = $10

        10.00 = $10

        20.01000089 = $20.01

        它是用Kotlin写的,作为Double的一个有趣的扩展(因为它在Android中使用),但是它可以很容易地转换为Java,因为使用了Java类。

        /**
         * 23.0 -> $23
         *
         * 23.1 -> $23.1
         *
         * 23.01 -> $23.01
         *
         * 23.99 -> $23.99
         *
         * 23.999 -> $24
         *
         * -0.0 -> $0
         *
         * -5.00 -> -$5
         *
         * -5.019 -> -$5.02
         */
        fun Double?.formatUserAsSum(): String {
            return when {
                this == null || this == 0.0 -> "$0"
                this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
                else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
            }
        }
        

        使用方法:

        var yourDouble: Double? = -20.00
        println(yourDouble.formatUserAsSum()) // will print -$20
        
        yourDouble = null
        println(yourDouble.formatUserAsSum()) // will print $0
        

        关于十进制格式https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

        【讨论】:

          【解决方案7】:

          这是我想出的:

            private static String format(final double dbl) {
              return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
            }
          

          它是一个简单的单行代码,只有在确实需要时才转换为 int。

          【讨论】:

          • 重复 Felix Edelmann 在其他地方所说的:这将创建一个与区域设置无关的字符串,这可能并不总是适合用户。
          • 公平点,对于我的用例来说,这不是问题,我现在不完全确定,但我认为可以使用 String.format(带有所需的语言环境)而不是 valueOf
          【解决方案8】:

          使用DecimalFormatsetMinimumFractionDigits(0)

          【讨论】:

          • 我会添加 setMaximumFractionDigits(2)setGroupingUsed(false) (OP 没有提到它,但从示例看来它是必需的)。此外,一个小的测试用例不会受到伤害,因为它在这种情况下是微不足道的。尽管如此,因为我认为它是最简单的解决方案,所以点赞就是点赞:)
          【解决方案9】:
          public static String fmt(double d) {
              String val = Double.toString(d);
              String[] valArray = val.split("\\.");
              long valLong = 0;
              if(valArray.length == 2) {
                  valLong = Long.parseLong(valArray[1]);
              }
               if (valLong == 0)
                  return String.format("%d", (long) d);
              else
                  return String.format("%s", d);
          }
          

          我不得不使用它,因为 d == (long)dSonarQube 报告中给了我违规行为。

          【讨论】:

            【解决方案10】:

            这个可以很好地完成工作:

                public static String removeZero(double number) {
                    DecimalFormat format = new DecimalFormat("#.###########");
                    return format.format(number);
                }
            

            【讨论】:

              【解决方案11】:

              我的两分钱:

              if(n % 1 == 0) {
                  return String.format(Locale.US, "%.0f", n));
              } else {
                  return String.format(Locale.US, "%.1f", n));
              }
              

              【讨论】:

              • 或者只是return String.format(Locale.US, (n % 1 == 0 ? "%.0f" : "%.1f"), n);
              • 在 23.00123 ==> 23.00 时失败
              • 你在做什么?它总是在点后四舍五入到 1 位,这不是问题的答案。为什么有些人看不懂?
              • 你的错误答案不会返回232 0.18 1237875192 4.58 0 1.2345
              • 它真的有效吗?什么是'n'?某种浮点数?一个整数?
              【解决方案12】:

              您说您选择double 类型存储您的号码。我认为这可能是问题的根源,因为它会迫使您将 整数 存储为双精度数(因此会丢失有关值性质的初始信息)。将您的数字存储在 Number 类(双精度和整数的超类)的实例中并依靠多态性来确定每个数字的正确格式怎么样?

              我知道因此重构整个代码部分可能是不可接受的,但它可以在没有额外代码/转换/解析的情况下产生所需的输出。

              例子:

              import java.util.ArrayList;
              import java.util.List;
              
              public class UseMixedNumbers {
              
                  public static void main(String[] args) {
                      List<Number> listNumbers = new ArrayList<Number>();
              
                      listNumbers.add(232);
                      listNumbers.add(0.18);
                      listNumbers.add(1237875192);
                      listNumbers.add(4.58);
                      listNumbers.add(0);
                      listNumbers.add(1.2345);
              
                      for (Number number : listNumbers) {
                          System.out.println(number);
                      }
                  }
              
              }
              

              将产生以下输出:

              232
              0.18
              1237875192
              4.58
              0
              1.2345
              

              【讨论】:

              • javascript 顺便做了同样的选择 :)
              • @Pyrolistical 你能解释一下你的陈述吗?这对我来说不是很清楚...... :)
              【解决方案13】:

              用途:

              if (d % 1.0 != 0)
                  return String.format("%s", d);
              else
                  return String.format("%.0f", d);
              

              这应该适用于 Double 支持的极值。它产生:

              0.12
              12
              12.144252
              0
              

              【讨论】:

              • 我更喜欢这个我们不需要进行类型转换的答案。
              • 简短解释:"%s" 基本上调用d.toString() 但它不适用于intd==null
              • 非常喜欢这个。
              【解决方案14】:

              简而言之:

              如果您想摆脱尾随零和locale 问题,那么您应该使用:

              double myValue = 0.00000021d;
              
              DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
              df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
              
              System.out.println(df.format(myValue)); //output: 0.00000021
              

              说明:

              为什么其他答案不适合我:

              • Double.toString()System.out.printlnFloatingDecimal.toJavaFormatString 如果 double 小于 10^-3 或大于或等于 10^7,则使用科学记数法

                 double myValue = 0.00000021d;
                 String.format("%s", myvalue); //output: 2.1E-7
                
              • 通过使用%f,默认的小数精度为 6,否则您可以对其进行硬编码,但如果您的小数较少,则会导致添加额外的零。示例:

                 double myValue = 0.00000021d;
                 String.format("%.12f", myvalue); // Output: 0.000000210000
                
              • 通过使用setMaximumFractionDigits(0);%.0f,您可以删除任何小数精度,这对于整数/长整数是可以的,但对于双精度数则不行

                 double myValue = 0.00000021d;
                 System.out.println(String.format("%.0f", myvalue)); // Output: 0
                 DecimalFormat df = new DecimalFormat("0");
                 System.out.println(df.format(myValue)); // Output: 0
                
              • 通过使用 DecimalFormat,您将依赖于本地。在法语语言环境中,小数点分隔符是逗号,而不是点:

                 double myValue = 0.00000021d;
                 DecimalFormat df = new DecimalFormat("0");
                 df.setMaximumFractionDigits(340);
                 System.out.println(df.format(myvalue)); // Output: 0,00000021
                

                使用英语语言环境可确保您获得一个小数点分隔符,无论您的程序将在何处运行。

              为什么要使用 340 来表示 setMaximumFractionDigits

              两个原因:

              • setMaximumFractionDigits 接受整数,但其实现允许的最大位数为 DecimalFormat.DOUBLE_FRACTION_DIGITS,等于 340
              • Double.MIN_VALUE = 4.9E-324 所以如果你有 340 位数字,你肯定不会舍入你的双精度数并丢失精度

              【讨论】:

              • 这不适用于整数,例如“2”变成“2”。
              • 谢谢,我已经通过使用模式0 而不是#. 修复了答案
              • 您没有使用常量DecimalFormat.DOUBLE_FRACTION_DIGITS,但您使用的值是340,然后您提供注释以表明它等于DecimalFormat.DOUBLE_FRACTION_DIGITS。为什么不直接使用常量???
              • 因为这个属性不是公开的......它是“包友好的”
              • 谢谢!事实上,这个答案是唯一真正符合问题中提到的所有要求的答案——它不会显示不必要的零,不会对数字进行四舍五入,并且取决于语言环境。太好了!
              【解决方案15】:

              这里有两种方法来实现它。首先,更短(可能更好)的方式:

              public static String formatFloatToString(final float f)
              {
                final int i = (int)f;
                if(f == i)
                  return Integer.toString(i);
                return Float.toString(f);
              }
              

              这是更长且可能更糟糕的方式:

              public static String formatFloatToString(final float f)
              {
                final String s = Float.toString(f);
                int dotPos = -1;
                for(int i=0; i<s.length(); ++i)
                  if(s.charAt(i) == '.')
                  {
                    dotPos = i;
                    break;
                  }
              
                if(dotPos == -1)
                  return s;
              
                int end = dotPos;
                for(int i = dotPos + 1; i<s.length(); ++i)
                {
                  final char c = s.charAt(i);
                  if(c != '0')
                    end = i + 1;
                }
                final String result = s.substring(0, end);
                return result;
              }
              

              【讨论】:

              • 有时,当你让事情变得更简单时,背后的代码会更复杂,优化程度也更低......但是,你可以使用大量的内置 API 函数......
              • 你应该从简单开始,一旦你确定你有性能问题,那么你应该优化。代码是供人类反复阅读的。让它跑得快是次要的。尽可能不使用标准 API,您更有可能引入错误,只会让未来更难更改。
              • 我认为你这样写的代码不会更快。 JVM 非常聪明,在您对其进行分析之前,您实际上并不知道某事物的速度有多快或有多慢。当出现问题时,可以检测并修复性能问题。您不应该过早地对其进行优化。编写代码供人们阅读,而不是您想象机器将如何运行它。一旦成为性能问题,请使用分析器重写代码。
              • 其他人编辑了答案以改进代码格式。我正在审查几十个编辑以供批准,并打算在这里批准他们的编辑,但编辑不一致,所以我修复了它们。我还改进了文本 sn-ps 的语法。
              • 我不明白。如果你说格式无关紧要,你为什么要花时间把它改回来?
              【解决方案16】:

              我创建了一个DoubleFormatter 以有效地将大量双精度值转换为漂亮/可呈现的字符串:

              double horribleNumber = 3598945.141658554548844;
              DoubleFormatter df = new DoubleFormatter(4, 6); // 4 = MaxInteger, 6 = MaxDecimal
              String beautyDisplay = df.format(horribleNumber);
              
              • 如果 V 的整数部分大于 MaxInteger => 以科学格式 (1.2345E+30) 显示 V。否则,以正常格式 (124.45678) 显示。
              • MaxDecimal 决定十进制位数(用bankers' rounding 修剪)

              代码如下:

              import java.math.RoundingMode;
              import java.text.DecimalFormat;
              import java.text.DecimalFormatSymbols;
              import java.text.NumberFormat;
              import java.util.Locale;
              
              import com.google.common.base.Preconditions;
              import com.google.common.base.Strings;
              
              /**
               * Convert a double to a beautiful String (US-local):
               *
               * double horribleNumber = 3598945.141658554548844;
               * DoubleFormatter df = new DoubleFormatter(4,6);
               * String beautyDisplay = df.format(horribleNumber);
               * String beautyLabel = df.formatHtml(horribleNumber);
               *
               * Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
               * (avoid to create an object NumberFormat each call of format()).
               *
               * 3 instances of NumberFormat will be reused to format a value v:
               *
               * if v < EXP_DOWN, uses nfBelow
               * if EXP_DOWN <= v <= EXP_UP, uses nfNormal
               * if EXP_UP < v, uses nfAbove
               *
               * nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
               *
               * @author: DUONG Phu-Hiep
               */
              public class DoubleFormatter
              {
                  private static final double EXP_DOWN = 1.e-3;
                  private double EXP_UP; // always = 10^maxInteger
                  private int maxInteger_;
                  private int maxFraction_;
                  private NumberFormat nfBelow_;
                  private NumberFormat nfNormal_;
                  private NumberFormat nfAbove_;
              
                  private enum NumberFormatKind {Below, Normal, Above}
              
                  public DoubleFormatter(int maxInteger, int maxFraction){
                      setPrecision(maxInteger, maxFraction);
                  }
              
                  public void setPrecision(int maxInteger, int maxFraction){
                      Preconditions.checkArgument(maxFraction>=0);
                      Preconditions.checkArgument(maxInteger>0 && maxInteger<17);
              
                      if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
                          return;
                      }
              
                      maxFraction_ = maxFraction;
                      maxInteger_ = maxInteger;
                      EXP_UP =  Math.pow(10, maxInteger);
                      nfBelow_ = createNumberFormat(NumberFormatKind.Below);
                      nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
                      nfAbove_ = createNumberFormat(NumberFormatKind.Above);
                  }
              
                  private NumberFormat createNumberFormat(NumberFormatKind kind) {
              
                      // If you do not use the Guava library, replace it with createSharp(precision);
                      final String sharpByPrecision = Strings.repeat("#", maxFraction_);
              
                      NumberFormat f = NumberFormat.getInstance(Locale.US);
              
                      // Apply bankers' rounding:  this is the rounding mode that
                      // statistically minimizes cumulative error when applied
                      // repeatedly over a sequence of calculations
                      f.setRoundingMode(RoundingMode.HALF_EVEN);
              
                      if (f instanceof DecimalFormat) {
                          DecimalFormat df = (DecimalFormat) f;
                          DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
              
                          // Set group separator to space instead of comma
              
                          //dfs.setGroupingSeparator(' ');
              
                          // Set Exponent symbol to minus 'e' instead of 'E'
                          if (kind == NumberFormatKind.Above) {
                              dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
                          } else {
                              dfs.setExponentSeparator("e");
                          }
              
                          df.setDecimalFormatSymbols(dfs);
              
                          // Use exponent format if v is outside of [EXP_DOWN,EXP_UP]
              
                          if (kind == NumberFormatKind.Normal) {
                              if (maxFraction_ == 0) {
                                  df.applyPattern("#,##0");
                              } else {
                                  df.applyPattern("#,##0."+sharpByPrecision);
                              }
                          } else {
                              if (maxFraction_ == 0) {
                                  df.applyPattern("0E0");
                              } else {
                                  df.applyPattern("0."+sharpByPrecision+"E0");
                              }
                          }
                      }
                      return f;
                  }
              
                  public String format(double v) {
                      if (Double.isNaN(v)) {
                          return "-";
                      }
                      if (v==0) {
                          return "0";
                      }
                      final double absv = Math.abs(v);
              
                      if (absv<EXP_DOWN) {
                          return nfBelow_.format(v);
                      }
              
                      if (absv>EXP_UP) {
                          return nfAbove_.format(v);
                      }
              
                      return nfNormal_.format(v);
                  }
              
                  /**
                   * Format and higlight the important part (integer part & exponent part)
                   */
                  public String formatHtml(double v) {
                      if (Double.isNaN(v)) {
                          return "-";
                      }
                      return htmlize(format(v));
                  }
              
                  /**
                   * This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
                   * not be used to format a great numbers of value
                   *
                   * We will never use this methode, it is here only to understanding the Algo principal:
                   *
                   * format v to string. precision_ is numbers of digits after decimal.
                   * if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
                   * otherwise display scientist format with: 1.2345e+30
                   *
                   * pre-condition: precision >= 1
                   */
                  @Deprecated
                  public String formatInefficient(double v) {
              
                      // If you do not use Guava library, replace with createSharp(precision);
                      final String sharpByPrecision = Strings.repeat("#", maxFraction_);
              
                      final double absv = Math.abs(v);
              
                      NumberFormat f = NumberFormat.getInstance(Locale.US);
              
                      // Apply bankers' rounding:  this is the rounding mode that
                      // statistically minimizes cumulative error when applied
                      // repeatedly over a sequence of calculations
                      f.setRoundingMode(RoundingMode.HALF_EVEN);
              
                      if (f instanceof DecimalFormat) {
                          DecimalFormat df = (DecimalFormat) f;
                          DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
              
                          // Set group separator to space instead of comma
              
                          dfs.setGroupingSeparator(' ');
              
                          // Set Exponent symbol to minus 'e' instead of 'E'
              
                          if (absv>EXP_UP) {
                              dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
                          } else {
                              dfs.setExponentSeparator("e");
                          }
                          df.setDecimalFormatSymbols(dfs);
              
                          //use exponent format if v is out side of [EXP_DOWN,EXP_UP]
              
                          if (absv<EXP_DOWN || absv>EXP_UP) {
                              df.applyPattern("0."+sharpByPrecision+"E0");
                          } else {
                              df.applyPattern("#,##0."+sharpByPrecision);
                          }
                      }
                      return f.format(v);
                  }
              
                  /**
                   * Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
                   * It is a html format of a number which highlight the integer and exponent part
                   */
                  private static String htmlize(String s) {
                      StringBuilder resu = new StringBuilder("<b>");
                      int p1 = s.indexOf('.');
              
                      if (p1>0) {
                          resu.append(s.substring(0, p1));
                          resu.append("</b>");
                      } else {
                          p1 = 0;
                      }
              
                      int p2 = s.lastIndexOf('e');
                      if (p2>0) {
                          resu.append(s.substring(p1, p2));
                          resu.append("<b>");
                          resu.append(s.substring(p2, s.length()));
                          resu.append("</b>");
                      } else {
                          resu.append(s.substring(p1, s.length()));
                          if (p1==0){
                              resu.append("</b>");
                          }
                      }
                      return resu.toString();
                  }
              }
              

              注意:我使用了 Guava 库中的两个函数。如果你不使用 Guava,请自己编写代码:

              /**
               * Equivalent to Strings.repeat("#", n) of the Guava library:
               */
              private static String createSharp(int n) {
                  StringBuilder sb = new StringBuilder();
                  for (int i=0; i<n; i++) {
                      sb.append('#');
                  }
                  return sb.toString();
              }
              

              【讨论】:

              【解决方案17】:

              最好的方法如下:

              public class Test {
              
                  public static void main(String args[]){
                      System.out.println(String.format("%s something", new Double(3.456)));
                      System.out.println(String.format("%s something", new Double(3.456234523452)));
                      System.out.println(String.format("%s something", new Double(3.45)));
                      System.out.println(String.format("%s something", new Double(3)));
                  }
              }
              

              输出:

              3.456 something
              3.456234523452 something
              3.45 something
              3.0 something
              

              唯一的问题是最后一个 .0 没有被删除。但是,如果您能够忍受这种情况,那么这种方法效果最好。 %.2f 会将其四舍五入到最后两位小数。 DecimalFormat 也是如此。如果您需要所有小数位,但不需要尾随零,那么这效果最好。

              【讨论】:

              • DecimalFormat 格式为 "#.##" 如果不需要,则不会保留额外的 0:System.out.println(new java.text.DecimalFormat("#.##").format(1.0005)); 将打印 1
              • 这就是我的观点。如果您希望显示 0.0005(如果有)怎么办。您会将其四舍五入为 2 位小数。
              • OP 询问如何打印存储在双精度中的整数值 :)
              【解决方案18】:
              String.format("%.2f", value);
              

              【讨论】:

              • 这是正确的,但即使没有小数部分,也总是打印尾随零。 String.format("%.2f, 1.0005) 打印 1.00 而不是 1。如果不存在小数部分,是否有任何格式说明符不打印?
              • 投了反对票,因为问题是要求去除所有尾随零,这个答案总是会留下两个浮点数,无论是否为零。
              • 我认为您可以通过使用 g 而不是 f 正确处理尾随零。
              • 我在带有“%.5f”的生产系统中使用了这个解决方案,它真的很糟糕,不要使用它...因为它打印的是:5.12E-4 而不是 0.000512
              • 虽然这与 OP 所要求的完全相反,但我很感激它存在于此,我正在寻找这个!
              【解决方案19】:

              不,没关系。字符串操作造成的性能损失为零。

              这是在%f之后修剪结尾的代码:

              private static String trimTrailingZeros(String number) {
                  if(!number.contains(".")) {
                      return number;
                  }
              
                  return number.replaceAll("\\.?0*$", "");
              }
              

              【讨论】:

              • 我投了反对票,因为您的解决方案不是最好的方法。看看 String.format。您需要使用正确的格式类型,在这种情况下浮动。看我上面的回答。
              • 我投了赞成票,因为我有同样的问题,这里似乎没有人理解这个问题。
              • 投反对票,因为 Tom 的帖子中提到的 DecimalFormat 正是您想要的。它非常有效地去除零。
              • 到上面,也许他想修剪零而不四舍五入?附言@Pyrolistical,当然你可以使用 number.replaceAll(".?0*$", ""); (当然是在 contains(".") 之后)
              • 好的,那么您将如何使用 DecimalFormat 实现我的目标?
              【解决方案20】:

              这是另一个答案,可以选择附加小数仅当小数不为零时。

                 /**
                   * Example: (isDecimalRequired = true)
                   * d = 12345
                   * returns 12,345.00
                   *
                   * d = 12345.12345
                   * returns 12,345.12
                   *
                   * ==================================================
                   * Example: (isDecimalRequired = false)
                   * d = 12345
                   * returns 12,345 (notice that there's no decimal since it's zero)
                   *
                   * d = 12345.12345
                   * returns 12,345.12
                   *
                   * @param d float to format
                   * @param zeroCount number decimal places
                   * @param isDecimalRequired true if it will put decimal even zero,
                   * false will remove the last decimal(s) if zero.
                   */
                  fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
                      val zeros = StringBuilder()
              
                      for (i in 0 until zeroCount) {
                          zeros.append("0")
                      }
              
                      var pattern = "#,##0"
              
                      if (zeros.isNotEmpty()) {
                          pattern += ".$zeros"
                      }
              
                      val numberFormat = DecimalFormat(pattern)
              
                      var formattedNumber = if (d != null) numberFormat.format(d) else "0"
              
                      if (!isDecimalRequired) {
                          for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
                              val number = formattedNumber[i - 1]
              
                              if (number == '0' || number == '.') {
                                  formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
                              } else {
                                  break
                              }
                          }
                      }
              
                      return formattedNumber
                  }
              

              【讨论】:

                【解决方案21】:
                new DecimalFormat("00.#").format(20.236)
                //out =20.2
                
                new DecimalFormat("00.#").format(2.236)
                //out =02.2
                
                1. 0 表示最小位数
                2. 呈现 # 位数

                【讨论】:

                • 虽然这可能会为问题提供解决方案,但最好为社区添加简短说明以从答案中受益(和学习)
                • 这不是该问题的答案。它总是在一个点后四舍五入到一个数字。如此糟糕的答案和离题
                • 你的错误答案不会返回232 0.18 1237875192 4.58 0 1.2345
                【解决方案22】:
                new DecimalFormat("#.##").format(1.199); //"1.2"
                

                正如 cmets 所指出的,这不是原始问题的正确答案。
                也就是说,这是一种非常有用的方式来格式化数字而没有不必要的尾随零。

                【讨论】:

                • 这里需要注意的是,1.1 可以正确格式化为“1.1”,没有任何尾随零。
                • 如果您碰巧想要特定数量的尾随零(例如,如果您要打印货币金额),那么您可以使用 '0' 而不是 '#' (即 new DecimalFormat("0.00") .format(amount);) 这不是 OP 想要的,但可能对参考有用。
                • 是的,作为问题的原作者,这是错误的答案。有趣的是有多少赞成票。这个解决方案的问题是它任意四舍五入到小数点后两位。
                • @Mazyod 因为您始终可以传入比格式更多小数的浮点数。那就是编写可以在大多数情况下工作但不能涵盖所有边缘情况的代码。
                • @Pyrolistical - 恕我直言,有很多支持,因为虽然这对您来说是错误的解决方案,但对于 99% 以上找到此问答的人来说,它是正确的解决方案:通常,最后几个数字双倍是“噪音”,使输出混乱,干扰可读性。因此,程序员确定有多少数字对阅读输出的人有益,并指定多少。常见的情况是累积了小的数学错误,因此值可能是 12.000000034,但更喜欢四舍五入到 12,并紧凑地显示为“12”。而“12.340000056”=>“12.34”。
                【解决方案23】:

                请注意,String.format(format, args...) 依赖于区域设置,因为它使用用户的默认区域设置,即可能使用逗号和甚至像 123 456,789123,456.789 之类的内部空格,这可能不是您所期望的。

                您可能更喜欢使用String.format((Locale)null, format, args...)

                例如,

                    double f = 123456.789d;
                    System.out.println(String.format(Locale.FRANCE,"%f",f));
                    System.out.println(String.format(Locale.GERMANY,"%f",f));
                    System.out.println(String.format(Locale.US,"%f",f));
                

                打印

                123456,789000
                123456,789000
                123456.789000
                

                这就是String.format(format, args...) 在不同国家/地区所做的事情。

                编辑好的,因为已经讨论过手续:

                    res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
                    ...
                
                protected static String stripFpZeroes(String fpnumber) {
                    int n = fpnumber.indexOf('.');
                    if (n == -1) {
                        return fpnumber;
                    }
                    if (n < 2) {
                        n = 2;
                    }
                    String s = fpnumber;
                    while (s.length() > n && s.endsWith("0")) {
                        s = s.substring(0, s.length()-1);
                    }
                    return s;
                }
                

                【讨论】:

                • 您应该将此作为评论添加到已接受的答案中
                • 评论不允许本附录的长度或格式。由于它添加了可能有用的信息,我认为它应该被允许而不是被删除。
                【解决方案24】:

                如果想法是打印存储为双精度的整数,就好像它们是整数一样,否则以最低必要精度打印双精度:

                public static String fmt(double d)
                {
                    if(d == (long) d)
                        return String.format("%d",(long)d);
                    else
                        return String.format("%s",d);
                }
                

                生产:

                232
                0.18
                1237875192
                4.58
                0
                1.2345
                

                并且不依赖字符串操作。

                【讨论】:

                • 同意,这是一个不好的答案,不要使用它。它无法使用大于最大int 值的double。即使使用long,它仍然会因大量数字而失败。此外,它将返回一个指数形式的字符串,例如“1.0E10”,对于较大的值,这可能不是提问者想要的。在第二个格式字符串中使用%f 而不是%s 来解决这个问题。
                • OP 明确表示他们不想要使用%f 格式化的输出。答案特定于所描述的情况和所需的输出。 OP 建议它们的最大值是 32 位无符号整数,我认为这意味着 int 是可以接受的(无符号实际上在 Java 中不存在,并且没有示例有问题),但是将 int 更改为 long 是如果情况不同,一个简单的修复。
                • 问题中哪里说不应该这样做?
                • String.format("%s",d)???谈论不必要的开销。使用Double.toString(d)。另一个也一样:Long.toString((long)d).
                • 问题是%s 不适用于语言环境。在德语中,我们使用“,”而不是“。”十进制数。 String.format(Locale.GERMAN, "%f", 1.5) 返回“1,500000”,String.format(Locale.GERMAN, "%s", 1.5) 返回“1.5”——带有“.”,这在德语中是错误的。是否也有依赖于语言环境的“%s”版本?
                【解决方案25】:

                在我的机器上,下面的函数比JasonD's answer提供的函数快大约7倍,因为它避开了String.format

                public static String prettyPrint(double d) {
                  int i = (int) d;
                  return d == i ? String.valueOf(i) : String.valueOf(d);
                }
                

                【讨论】:

                • 嗯,这没有考虑语言环境,但 JasonD 也没有。
                【解决方案26】:

                这是一个实际有效的答案(此处结合不同的答案)

                public static String removeTrailingZeros(double f)
                {
                    if(f == (int)f) {
                        return String.format("%d", (int)f);
                    }
                    return String.format("%f", f).replaceAll("0*$", "");
                }
                

                【讨论】:

                • 您没有替换 POINT,例如“100.0”将转换为“100”。
                • if(f == (int)f) 负责。
                • 在 f = 9999999999.00 时失败
                【解决方案27】:
                String s = String.valueof("your int variable");
                while (g.endsWith("0") && g.contains(".")) {
                    g = g.substring(0, g.length() - 1);
                    if (g.endsWith("."))
                    {
                        g = g.substring(0, g.length() - 1);
                    }
                }
                

                【讨论】:

                • 您应该只搜索右边的第一个非零数字,然后使用子字符串(当然还要验证字符串是否包含“.”)。这样,您就不会在途中创建这么多临时字符串。
                【解决方案28】:
                String s = "1.210000";
                while (s.endsWith("0")){
                    s = (s.substring(0, s.length() - 1));
                }
                

                这将使字符串删除拖尾 0-s。

                【讨论】:

                • 这是一个很好的问题解决方案,如果他们只对删除尾随零感兴趣,您将如何更改代码以同时修剪尾随小数点?即“1。”
                • 小心,你的解法会把1000转换成1,这是错误的。
                猜你喜欢
                • 2020-08-04
                • 1970-01-01
                • 1970-01-01
                • 2013-06-02
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-09-24
                相关资源
                最近更新 更多