如何在Java中使用StringTemplate(ST)格式化十进制数?

3

我正在使用Java中的StringTemplate。

我希望以特定精度(例如小数点后3位)呈现十进制数字。

ST对象是否可以做到这一点?如何实现?

编辑:为了澄清,当呈现对象时尤其相关。例如,我的代码如下:

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

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

3个回答

11

注册内置的NumberRenderer以支持Number子类,然后使用格式选项:

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

请考虑包含此类模板的预期呈现方式。 - user166390

3

虽未经测试,但我猜类似以下代码应该可行:

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 并不负责格式化任何给定的值,因为已经存在可以完成这个任务的类。 - Yanick Rochon
这就是我所做的,但我希望StringTemplate能为此提供一种快捷方式。 - daphshez
9
我不同意。模型的工作是提供一个数值;视图的工作是决定如何展示它。小数点后的位数是一种呈现细节,而不是逻辑或存储的一部分。 - Kricket

0

编辑:我太蠢了,链接就在我给出的链接上面。使用像这里给出的示例一样的渲染器

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

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来处理双精度浮点数(或其他类型),并让它根据请求的属性名称确定精度,从而拼凑出一些东西。model adaptors

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接