如何在显示标签中格式化货币
Posted
技术标签:
【中文标题】如何在显示标签中格式化货币【英文标题】:how to format currency in displaytag 【发布时间】:2009-06-22 15:54:16 【问题描述】:我得到了 4567.00、8976.00 等金额的值。现在,在 displaytag 中显示此值时,我想将其打印为 4567.00 美元,而不仅仅是 4567.00。我怎样才能做到这一点? 如果我只想使用显示标签。我可以使用 core:out 标签来达到同样的效果。
$<core:out value="$variableInMyList" />
找到答案 [我是怎么做到的]
创建一个新类:
public class NumberFormatDecorator implements DisplaytagColumnDecorator
Logger logger = MyLogger.getInstance ( );
public Object decorate(Object columnValue, PageContext pageContext, MediaTypeEnum media) throws DecoratorException
try
Object colVal = columnValue;
if ( columnValue != null )
colVal = Double.parseDouble( (String)columnValue );
return colVal;
catch ( Exception nfe )
logger.error( "Unable to convert to Numeric Format");
return columnValue; // even if there is some exception return the original value
现在在显示标签中
<displaytag:column title="Amount" property="amount" decorator="com.rj.blah.utils.decorator.NumberFormatDecorator" format="$ 0,number,0,000.00"/>
注意:我们可以在displaytag:column的format属性中使用MessageFormat
【问题讨论】:
【参考方案1】:你需要你的班级做什么? 你可以这样写:
<displaytag:column property="amount" format="$ 0,number,0,000.00"/>
【讨论】:
如果属性的类型是字符串而不是数字,您将如何格式化货币。我试过$ 0,string,0,000.00
和 $ 0,String,0,000.00
但没有用。【参考方案2】:
DisplayTab 对 JSTL 或 EL 不太友好,并且不支持那种格式的格式。相反,您需要扩展 TableDecorator 类并使用 display:table 标记的 decorator 属性对其进行引用。
您的装饰器子类应该为您的格式化货币列定义一个 getter 方法,例如:
public class MyTableDecorator extends TableDecorator
public String getCurrency()
MyRowType row = getCurrentRowObject();
return row.getCurrency.format();
和
<display:table name="myList" decorator="test.MyTableDecorator">
<display:column property="myProperty" title="My Property"/>
<display:column property="currency" title="Currency"/>
</display:table>
或者,您可以实现 DisplaytagColumnDecorator 接口,并从 JSP 中引用该装饰器:
<display:table name="myList">
<display:column property="myProperty" title="My Property"/>
<display:column property="currency" title="Currency" decorator="test.MyColumnDecorator"/>
</display:table>
更多信息请参见the documentation
【讨论】:
【参考方案3】:你可以使用装饰器。
你会有类似的东西
class myDecorator extends TableDecorator
public String getCurrency()
MyClass myClass = (MyClass)getCurrentRow();
return "$"+myClass.getCurrency;
检查出来! http://displaytag.sourceforge.net/10/tut_decorators.html
如果你不想使用装饰器,你可以使用 id 属性和 JSTL
<display:table htmlId="list" name="mylist" id="row">
<display:column>
<%-- row is your current list object. row.currency calls getCurrency()
$ goes right out to HTML
--%>
$ <c:out="$row.currency"/>
</display:column>
</display:table>
来自display:tag tag reference
id:见 uid
uid:用于标识此的唯一 id 桌子。代表的对象 当前行也被添加到 此名称下的 pageContext 和 当前行号是使用 键 uid_rowNum。两个表在同一个 页面不能有相同的 uid(分页 和排序会影响两者)。如果不 “htmlId”被指定为相同的值 将用于 html id 生成表
【讨论】:
$这是我使用的:
<d:column title="Cost" property="cost" format="0,number,currency" sortable="true"/>
【讨论】:
以上是关于如何在显示标签中格式化货币的主要内容,如果未能解决你的问题,请参考以下文章