背景:html
spring后端输出double类型数据,前端使用thymeleaf框架,格式化double数据类型,因为须要显示原值(好比原来录入5,而不能显示5.00),所以须要存储数值(存储值为decimal类型,其中2位小数)小数点后面进行去零处理,而不能采用thymeleaf自己的格式化方式。前端
思路:java
1.尝试thymeleaf自己自带函数解决,未果(thymeleaf自己方法处理没法去除小数点后面的0,只能显示固定的小数点位数)。web
2.采用JS解决,感受有些麻烦,并且与thymeleaf结合也较困难,做罢。spring
3.因为Java后台处理比较擅长处理数值格式化问题,而thymeleaf也正巧在服务端完成解析标签工做,那么可否让thymeleaf框架调用Java方法呢?理论上是可行的,通过不断摸索,终于实验成果。apache
4.扩展thymeleaf标签后端
通过对比发现,方法3实现较简单,具体作法以下:框架
实现方法:函数
方法1:thymeleaf框架调用Java静态方法:spa
编写一个Java类,里面写一个静态方法,用于处理double类型数据格式化,返回字符串。详细代码以下:
package com.hw.ibweb.util; import org.apache.http.util.TextUtils; import java.math.BigDecimal; import java.text.DecimalFormat; /** * Created by clyan on 2019/10/23 10:08. */ public class FormatUtil { /** * double小数点格式化 * @param value * @return */ public static String valueFormat(double value) { DecimalFormat df = new DecimalFormat("#####.##"); String xs = df.format(new BigDecimal(value)); return xs; } }
而后,在相关html中,采用以下写法:
<input type="text" class="form-control" width="250px" maxlength="6" placeholder="最长6位数字" name="code" th:attr="id=${item.dcitCode}" th:value="${T(com.hw.ibweb.util.FormatUtil).valueFormat(item.money)}" aria-label="Text input with checkbox"/>
即,采用thymeleaf框架的${T(fullclasspath).function()}接口解决,结果以下:
至此,thymeleaf框架调用Java静态方法的思路已经实现,那么thymeleaf框架可否调用Java实例方法呢?通过实践发现,也是没问题的。
方法二:thymeleaf调用Java实例方法:
实例方法:
package com.hw.ibweb.util; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.text.DecimalFormat; /** * Created by clyan on 2019/10/10 11:57. */ public class bbb { public String valueFormat(double value) { DecimalFormat df = new DecimalFormat("#####.##"); String xs = df.format(new BigDecimal(value)); return xs; } }
在html页面中,调用该方法写法以下:
<input type="text" class="form-control" width="250px" maxlength="6" placeholder="最长6位数字" name="code" th:attr="id=${item.dcitCode}" th:value="${new com.hw.ibweb.util.bbb().valueFormat(item.money)}" aria-label="Text input with checkbox"/>
最终能效果也如预期:
至此,完整解决double数值格式化问题。