【问题标题】:How to format a number to include a "+/-" only when it is Not 0?如何格式化数字以仅在非 0 时包含“+/-”?
【发布时间】:2015-06-10 04:33:26
【问题描述】:

我想显示带有 +/- 符号的 double 数字,我为此使用这种十进制格式

double d = 0;
    DecimalFormat nf = new DecimalFormat("+#0.0;-#0.0");
    System.out.println(nf.format(d));

    d = -1;
    System.out.println(nf.format(d));

    d = 1;
    System.out.println(nf.format(d));

而我就是这样输出的

+0.0
-1.0
+1.0

但我想要0.0 没有+ 的标志

 0.0
-1.0
+1.0

谢谢

【问题讨论】:

  • 我不真的确定为什么不赞成..
  • 我也卡在这里..如果有人有解决方案请告诉我。

标签: java decimalformat


【解决方案1】:

也许更好更简单的代码:

String style = d > 0 ? "+%.2f" : "% .2f";
System.out.println(String.format(style, d));

【讨论】:

    【解决方案2】:

    this 一样,我不完全确定是否有办法使用 十进制格式来解决此问题,但是对该答案中给出的正则表达式稍作修改(再次,信用: @Bohemian) 似乎解决了这个问题。

    System.out.println(nf.format(d).replaceAll("^[-+](?=0(.0*)?$)", ""));
    

    这只是查找数字 0 格式的数字(即 0 后跟一些小数点后的零),并删除它前面的符号。

    【讨论】:

      【解决方案3】:

      如果您在此论坛上搜索,您的问题已经存在答案。答案在https://stackoverflow.com/a/11929642/4284989

      仅使用格式符号无法满足您的要求。应用格式后,您必须将符号符号替换为“”(空)。

      为清楚起见,下面的 sn-p 将为您提供所需的答案。

      public class FormatTester {
      public static void main(String[] args){
      
      DecimalFormat nf = new DecimalFormat("#,##0.0");
      String formattedValue = nf.format(Double.parseDouble(args[0]));
      formattedValue = formattedValue.replaceAll( "^-(?=0(.0*)?$)", "");
      
      System.out.println(">>>> "+formattedValue+" <<<<");    
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2020-04-01
        • 2020-05-03
        • 2018-08-09
        • 2014-09-01
        • 2015-11-13
        • 1970-01-01
        相关资源
        最近更新 更多