How to control significant digits, ONLY when necessary, in a Thymeleaf template?
java, spring, spring-mvc, thymeleaf
Solution
Hi you could try something like this.
<span th:text="${user.averageScore} % 1 == 0? ${user.averageScore} :${#numbers.formatDecimal(user.averageScore, 0, 2)}"/>
Problem
When using the `th:text` attribute to evaluate and render a numeric field, Thymeleaf displays the full number of digits available. For example, this: ``` <span th:text="${user.averageScore}"/> ``` ... might render on the browser screen: ``` 107.54896 ``` I would like to display this amount rounded to no more than two decimal places. From the Thymeleaf documentation, this: ``` <span th:text="${#numbers.formatDecimal(user.averageScore, 0, 2)}"/> ``` ... changes the output to this: ``` 107.55 ``` However, is there a way to make this more flexible... in cases where the value has FEWER than than two decimal places? I only want to remove decimal places, to get down to two. I never want to ADD decimal places, to get up to two. If the field above has a value of 107, then it would render as: ``` 107.00 ``` How can I make Thymeleaf format numbers for two decimal places, or less... rather than just two decimal places, no matter what?