2017-03-04 96 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'} 

这应该格式化数量以两位数字的字符串,您可以执行对结果字符串比较。

这可能是必要的,因为浮点比较可能有非常小的舍入误差,导致严格比较失败。格式化为字符串将数字四舍五入到更小的小数位数,并消除导致比较失败的小错误。