【问题标题】:Stop DecimalFormat with percentage sign from moving the decimal用百分号停止 DecimalFormat 移动小数
【发布时间】:2014-01-14 20:17:07
【问题描述】:

有没有办法防止DecimalFormat 对象自动将小数点向右移动两位?

这段代码:

double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));

产生:

65.87
6,587.00 %

但我希望它产生:

65.87
65.87 %

【问题讨论】:

    标签: java decimalformat


    【解决方案1】:

    用单引号将您的 % 括起来:

    DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
    

    【讨论】:

    • 我看到它有效,但为什么它有效?单引号在做什么?
    • @ryvantage 来自 JavaDoc (docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) - Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. They must be quoted, unless noted otherwise, if they are to appear in the prefix or suffix as literals.
    • @ryvantage MikeB 确实击败了我的解释,但这实际上是在逃避你的任意字符。其他类型的模式匹配也是如此 - 例如SimpleDateFormat
    • 啊,我明白了。所以SimpleDateFormatMMM d, 'Y' 看起来像Jan 14, Y。有道理。
    • @JVMATL 好吧,我猜 MikeB 以一种更简洁的方式解决了这个问题 :)
    【解决方案2】:

    默认情况下,当您在格式字符串中使用 % 时,要格式化的值将首先乘以 100。您可以使用 DecimalFormat.setMultiplier() 方法将乘数更改为 1。

    double d = 65.87;
    DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
    df2.setMultiplier(1);
    System.out.println(df2.format(d));
    

    生产

     65.87 %
    

    【讨论】:

      【解决方案3】:

      这就是我的做法:

      // your double in percentage:
      double percentage = 0.6587;
      
      // how I get the number in as many decimal places as I need:
      double doub = (100*10^n*percentage);
      System.out.println("TEST:   " + doub/10^n + "%");
      

      其中 n 是您需要的小数位数。

      我知道这不是最干净的方法,但它确实有效。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2017-09-30
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多