【问题标题】:Unreliable behavior in Thymeleaf's th:selected attributeThymeleaf 的 th:selected 属性中的不可靠行为
【发布时间】:2017-07-24 06:18:36
【问题描述】:

我有一个项目使用 Spring Boot 和 Thymeleaf 来呈现 html 页面。在其中一个页面中,我有以下 html 让 Thymeleaf 选择一个选项:

<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>

如果警告等于 0.5 或 0.75,Thymeleaf 会按预期工作,但如果警告等于 0.9 或 0.95,Thymeleaf 不会将 selected 属性添加到该选项。我添加了以下选项以查看我的警告值是否错误:

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

但在每种情况下,Thymeleaf 都正确显示 0.9 或 0.95。

感谢您的帮助。在过去的一个小时里,这让我发疯了。

【问题讨论】:

  • 这可能是因为您的浮点比较中的舍入错误。您可以尝试将警告值四舍五入为两位数并作为字符串进行比较,或者确定您是否可以在表达式中使用 Apache Commons Precision.compareTo()。
  • @Kylos 谢谢你的建议。你是对的,虽然我改用 value.compareTo(warning) == 0 来修复它。

标签: spring spring-boot thymeleaf


【解决方案1】:

我会推荐尝试

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

这应该将数字格式化为带有两位小数的字符串,以便您对结果执行字符串比较。

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

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2012-04-01
    • 2017-05-10
    相关资源
    最近更新 更多