Thymeleaf - 仅使用两位小数格式化百分比

Dav*_*ave 5 java formatting bigdecimal percentage thymeleaf

我正在尝试使用 Thymeleaf 格式化百分比。但是,对于 99.99 这样的 %,thymeleaf 将此值格式化为 100。我不想要它。

我这样做了:

Java端

BigDecimal percentage = (a).multiply(new BigDecimal(100)).divide(b, 3, RoundingMode.HALF_DOWN);
Run Code Online (Sandbox Code Playgroud)

百里香侧

th:text="${#numbers.formatDecimal(percentage, 1, 'POINT', 2, 'COMMA')}"
Run Code Online (Sandbox Code Playgroud)

如果百分比是 99.99 Thymeleaf 给我 100.00

为什么?

Dim*_*San 0

发生这种情况是因为Java 端percentagescale值大于decimalDigitsThymeleaf 端的值。

尝试将其设置为相同的值(2):

BigDecimal percentage = (a).multiply(new BigDecimal(100)).divide(b, 2, RoundingMode.HALF_DOWN);
Run Code Online (Sandbox Code Playgroud)

而且就像您percentage仅使用字段来显示百分比一样,我认为您不需要thousandsPointType参数('POINT'在您的情况下),因为它的值永远不会大于 100。