如何在 Java 中使用 StringTemplate (ST) 格式化十进制数字?
我在 Java 中使用 StringTemplate。
我想以一定的精度渲染十进制数(例如小数点后 3 位数字)。
ST 对象可以做到这一点吗?又如何呢?
编辑: 需要澄清的是,这在渲染对象时尤其重要。例如,我的代码看起来像
String renderMe(String template, Collection<MyClass> items)
{
// render the items here using the template....
}
renderMe() 不必知道有关 MyClass 字段的任何信息,特别是它不必知道哪些字段是浮点。我正在寻找一种维持这种解耦的解决方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为 Number 子类注册内置 NumberRenderer,然后使用格式选项:
Register built-in NumberRenderer for Number subclasses and then use format option:
未经测试,但我想这样的事情应该有效:
Not tested, but I guess something like this should work:
编辑:愚蠢的我,链接就在我给出的链接的正上方。使用渲染器,如此处给出的示例。
如果您提前知道需要哪些精度,则可以设置一个控制器来处理这些情况,并将它们推送到视图中。
飞溅提出了一种可以做到这一点的方法。一种更通用的方法可能如下所示:
您可以像这样设置 ST:
最后,如果您确实需要它完全通用,您可以使用 模型适配器 通过注册一个 ModelAdaptor 来处理双精度数(或其他),并让它根据请求的 propertyName 计算出精度。
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:
You would setup ST like:
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.