Velocity的数值类型,在页面显示的时候,系统会调用toString,自动将它们转换成字符串类型。
那么,在JSP页面里,怎么进行数值类型的运算呢?其实,很简单,可直接进行运算,如下:
- #set($result=${cpsIncome}/${newUserCount})
然后,将计算结果($result),在页面中显示。
运算结果(0.12979978058145913)默认的小数位数很长,如何保留两位小数呢?
Velocity已经提供了很完善的工具(velocity-tools),用它即可。下面是使用方法:
1、在Struts的配置文件(struts.xml)中,指定该工具的配置文件的位置。
- <struts>
- <constant name="struts.velocity.toolboxlocation" value="WEB-INF/toolbox.xml" />
- </struts>
2、修改该工具的配置文件,添加自己所需的工具(比如NumberTool)。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
- <toolbox>
- <tool>
- <key>NumberTool</key>
- <scope>application</scope>
- <class>org.apache.velocity.tools.generic.NumberTool</class>
- </tool>
- <tool>
- <key>NumericTool</key>
- <scope>application</scope>
- <class>com.yunlan.desktop.back.tool.NumericTool</class>
- </tool>
- </toolbox>
3、然后,在JSP页面里,即可使用该工具,进行各种格式化了。
- $NumberTool.format("#0.00",$result)
注意:如果Velocity自带的工具类,不能满足我们的需求,那么,可以使用自己定义的格式化类(比如上述配置里的NumericTool)。
1、自定义的NumericTool类的实现源码。
- package com.yunlan.desktop.back.tool;
- public class NumericTool {
- /**
- * 将浮点数小数,固定保留两位小数
- */
- public static String toFixedNumber(Double d) {
- if (d == null) {
- return "";
- }
- String valStr = String.format("%1$.2f", d);
- return valStr;
- }
- }
2、在JSP页面里,使用自定义的NumericTool类。
- $NumericTool.toFixedNumber($result)
日期的格式化,跟数值的格式,基本类似,具体可参考官方文档。
官方文档:http://velocity.apache.org/tools/devel/
From: http://blog.csdn.net/gaojinshan/article/details/38850721