【问题标题】:java equivalent to printf("%*.*f")java等价于printf("%*.*f")
【发布时间】:2012-09-11 18:31:32
【问题描述】:

在 C 中,printf() 语句允许在参数列表中提供精度长度。

printf("%*.*f", 7, 3, floatValue);

星号分别替换为第一个和第二个值。

我正在寻找 Android/Java 中的等价物; String.format() 抛出异常。

编辑:谢谢,@Tenner;它确实有效。

【问题讨论】:

    标签: java android printf string.format


    【解决方案1】:

    我用

    int places = 7;
    int decimals = 3;
    
    String.format("%" + places + "." + decimals + "f", floatValue);
    

    有点难看(和字符串连接使其性能不佳),但它可以工作。

    【讨论】:

      【解决方案2】:
      System.out.print(String.format("%.1f",floatValue));
      

      这会打印精度为 1 位小数的 floatValue

      【讨论】:

      【解决方案3】:

      你可以格式化格式:

      String f = String.format("%%%d.%df", 7, 3);
      System.out.println(f);
      System.out.format(f, 111.1111);
      

      这将输出:

      %7.3f
      111,111
      

      你也可以使用这样的小助手:

      public static String deepFormatter(String format, Object[]... args) {
          String result = format;
          for (int  i = 0; i != args.length; ++i) {
              result = String.format(result, args[i]);
          }
      
          return result;
      }
      

      随后的调用将等同于上面的代码并返回111,111

      deepFormatter("%%%d.%df", new Object[] {7, 3}, new Object[] {111.1111});
      

      它不如 printf 漂亮,而且输入格式可能会变得混乱,但你可以用它做更多事情。

      【讨论】:

        【解决方案4】:

        是这样的……

        %AFWPdatatype
        

        A - 参数数量

        F - 标志

        W - 宽度

        P - 精度

        String.format("%.1f",float_Val);

        【讨论】:

          猜你喜欢
          • 2011-02-06
          • 2021-09-23
          • 2010-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-16
          相关资源
          最近更新 更多