开发者

How to format decimal numbers with StringTemplate (ST) in Java?

I am using StringTemplate in Java.

I would like to render decimal number with a certain precision (e.g. 3 digits after the decimal point).

Is it possible to for the ST object to do it? And how?

Edit: to clarify, this is especially relevant when rendering objects. E.g. my code looks like

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

renderMe() doesn't have to know anything about t开发者_如何学Pythonhe fields of MyClass, in particular it doesn't have to know which fields are floating points. I am looking for a solution that maintains this decoupling.


Register built-in NumberRenderer for Number subclasses and then use format option:

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


Not tested, but I guess something like this should work:

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);


EDIT: stupid me, the link was directly above the one I gave. Use a Renderer like the example given here.

If you know ahead of time which precisions will be needed, you can set up a Controller to handle those cases, and push them into the View.

splash suggested a way that this could be done. A somewhat more generic way might be something like the following:

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
}

You would setup ST like:

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

Finally, if you really need it to be totally generic, you could hack something together with model adaptors by registering a ModelAdaptor to handle doubles (or whatever), and having it figure out the precision based on the requested propertyName.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜