2017-03-04 98 views
1

我有一個項目使用Spring Boot MVC和Thymeleaf來呈現html頁面。在一個頁面中,我有以下的HTML有Thymeleaf選擇一個選項:Thymeleaf的th:不可靠的行爲:選擇屬性

<select name="value" 
     id="usersWarning"> 
    <option value="0" th:text="#{button.disabled}">0</option> 
    <option value="0.5" th:selected="${warning} == 0.5">50%</option> 
    <option value="0.75" th:selected="${warning} == 0.75">75%</option> 
    <option value="0.9" th:selected="${warning} == 0.9">90%</option> 
    <option value="0.95" th:selected="${warning} == 0.95">95%</option> 
</select> 

Thymeleaf按預期工作,如果警告等於0.5或0.75,但如果警告等於0.9或0.95,Thymeleaf不添加「選擇「屬性到該選項。我增加了以下選項,看看我的警告值是錯誤的:

<option th:text="${warning}"></option> 

,但在每種情況下Thymeleaf顯示0.9或0.95正確。

謝謝你的幫助。這在最後一個小時裏讓我瘋狂。

+0

這可能是因爲你的浮點比較舍入錯誤。您可以嘗試將警告的值四捨五入作爲字符串進行比較,或者確定是否可以在表達式中使用Apache Commons Precision.compareTo()。 – Kylos

+1

@Kylos感謝您的建議。你是對的,雖然我通過使用value.compareTo(warning)== 0來解決它。 –

回答

1

我會建議您嘗試

${#numbers.formatDecimal(warning, 0, 2) == '0.95'} 

這應該格式化數量以兩位數字的字符串,您可以執行對結果字符串比較。

這可能是必要的,因爲浮點比較可能有非常小的舍入誤差,導致嚴格比較失敗。格式化爲字符串將數字四捨五入到更小的小數位數,並消除導致比較失敗的小錯誤。