thymeleafceil

How do I round a decimal result up in Thymeleaf (same behavior as Math.ceil)?


I am doing table pagination logic for my project using Thymeleaf.

I have two values:

  1. int totalRows
  2. int rowsPerPage

The operation I want to do is something along the lines of Math.ceil((1.0 + totalRows) / rowsPerPage) to store in a variable that represents the total number of pages necessary.

However, I'm not sure how to do that ceil() operation to convert it from a decimal to an integer.


Solution

  • If you are working with Spring then you can add a bean that has the method you want Math.ceil. Then call this method in the template. Something like

    @Component
    public class ThymeMath {
        public int ceil(int a, int b) {
            return Math.ceil....
        }
    }
    

    Then in the template

    ${@thymeMath.ceil(a, b)}
    

    That is in the case you really need to do it in Thymeleaf. In the more general case you can calculate the variable in the Java code and add it to the model.