问题
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 the 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.
回答1:
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());
回答2:
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);
回答3:
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.
来源:https://stackoverflow.com/questions/6610721/how-to-format-decimal-numbers-with-stringtemplate-st-in-java