【问题标题】:How to format decimal numbers with StringTemplate (ST) in Java?如何在 Java 中使用 StringTemplate (ST) 格式化十进制数?
【发布时间】:2011-09-30 10:38:05
【问题描述】:

我在 Java 中使用 StringTemplate。

我想以一定的精度呈现十进制数(例如小数点后 3 位)。

ST对象可以做到吗?如何?

编辑: 澄清一下,这在渲染对象时尤其重要。例如。我的代码看起来像

String renderMe(String template, Collection<MyClass> items)
{
  // render the items here using the template.... 
}

renderMe() 不必知道 MyClass 的字段,特别是它不必知道哪些字段是浮点数。我正在寻找一种能够保持这种解耦的解决方案。

【问题讨论】:

    标签: java stringtemplate


    【解决方案1】:

    为 Number 子类注册内置 NumberRenderer,然后使用格式选项:

    String template =
        "foo(x,y) ::= << <x; format=\"%,d\"> <y; format=\"%,2.3f\"> >>\n";
    STGroup g = new STGroupString(template);
    g.registerRenderer(Number.class, new NumberRenderer());
    

    【讨论】:

    • 考虑还包括此类模板的预期呈现。
    【解决方案2】:

    未经测试,但我想这样的东西应该可以工作:

    StringTemplate strTemp = new StringTemplate("Decimal number: $number$");
    NumberFormat nf = NumberFormat.getInstance();
    ((DecimalFormat)nf).applyPattern("0.000");
    strTemp.setAttribute("number", nf.format(123.45678));
    System.out.println(strTemp);
    

    【讨论】:

    • +1 是的,格式化任何给定值不是StringTemplate 的责任,因为已经有现有的类可以这样做。
    • 这就是我所做的,但我希望我的 StringTemplate 提供了一个快捷方式。
    • 我不同意。模型的工作是提供一个数值; View 的工作是决定如何呈现它。小数位数是表示细节,不是逻辑或存储的一部分。
    【解决方案3】:

    编辑:愚蠢的我,链接就在我提供的链接的正上方。使用Renderer like the example given here

    如果您提前知道需要哪些精度,您可以设置一个控制器来处理这些情况,并将它们推送到视图中。

    splash 提出了一种可以做到这一点的方法。一种更通用的方式可能类似于以下内容:

    class DoublePrecisionGetters {
      public double number;
      public NumberFormat nf = NumberFormat.getInstance();
    
      public DoublePrecisionGetters(double d)
      { number = d; }
    
      public String getTwoPlaces() {
        nf.applyPattern("0.00");
        return nf.format(number);
      }
    
      public String getThreePlaces() {
        nf.applyPattern("0.000");
        return nf.format(number);
      }
    
      // etc
    }
    

    你会像这样设置 ST:

    ST template = new ST("two places: $number.twoPlaces$", '$');
    template.setAttribute("number", new DoublePrecisionGetters(3.14159));
    

    最后,如果你真的需要它是完全通用的,你可以通过注册一个 ModelAdaptor 来处理双精度(或其他),并让它根据请求的 propertyName 计算出精度,来与 model adaptors 一起破解一些东西。

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      相关资源
      最近更新 更多