背景:
spring后端輸出double類型數據,前端使用thymeleaf框架,格式化double數據類型,由於需要顯示原值(比如原來錄入5,而不能顯示5.00),因此需要存儲數值(存儲值為decimal類型,其中2位小數)小數點后面進行去零處理,而不能采用thymeleaf本身的格式化方式。
思路:
1.嘗試thymeleaf本身自帶函數解決,未果(thymeleaf本身方法處理無法去除小數點后面的0,只能顯示固定的小數點位數)。
2.采用JS解決,感覺有些麻煩,而且與thymeleaf結合也較困難,作罷。
3.由於Java端比較擅長處理數值格式化問題,而thymeleaf也正巧在服務端完成解析標簽工作,那么能否讓thymeleaf框架調用Java方法呢?理論上是可行的,經過不斷實踐,終於實驗成功。
4.擴展thymeleaf標簽
經過對比發現,方法3實現較簡單,具體做法如下:
實現方法:
方法1:thymeleaf框架調用Java靜態方法:
編寫一個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數值格式化問題。