如何在Java中使用StringTemplate(ST)格式化十进制数字? [英] How to format decimal numbers with StringTemplate (ST) in Java?

查看:215
本文介绍了如何在Java中使用StringTemplate(ST)格式化十进制数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用StringTemplate.

I am using StringTemplate in Java.

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

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

ST对象可以这样做吗?如何?

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

要澄清的是,这在渲染对象时特别重要.例如.我的代码看起来像

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()不必了解有关MyClass字段的任何信息,特别是它不必知道哪些字段是浮点数.我正在寻找维持这种解耦的解决方案.

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.

推荐答案

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

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

这篇关于如何在Java中使用StringTemplate(ST)格式化十进制数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆