Search code examples
springspring-bootthymeleaf

Unreliable behavior in Thymeleaf's th:selected attribute


I have a project using Spring Boot and Thymeleaf for rendering html pages. In one of the pages, I have the following html to have Thymeleaf select an option:

<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 works as expected if warning equals 0.5 or 0.75, but if warning equals 0.9 or 0.95, Thymeleaf does not add the selected attribute to that option. I added the following option to see if my warning values are wrong:

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

but in each case Thymeleaf shows 0.9 or 0.95 correctly.

Thank you for your help. This has been driving me crazy for the last hour.


Solution

  • I would recommend trying

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

    This should format the number as a string with two decimal digits allowing you to perform string comparison on the result.

    This might be necessary because floating point comparisons can have very small rounding errors that cause a strict comparison to fail. Formatting as string rounds the number to fewer decimal places and gets rid of the small error that would otherwise cause the comparison to fail.