How to convert string into integer in the Velocity template?

Solution 1:

Aha! Been there.

#set($intString = "9")
#set($Integer = 0)
$Integer.parseInt($intString)

Doing this uses the java underlying velocity. The $Integer variable is nothing more that a java Integer object which you can then use to access .parseInt

Edit: The above code is for demonstration. Of course there are ways to optimize it.

Solution 2:

If you have some control over the velocity context, here's an alternative that alleviates the need to set a variable in the Velocity template.

Context velocityContext = new Context();
velocityContext.put(Integer.class.getSimpleName(), Integer.class);

This allows you to call the static methods of java.lang.Integer in your template using $Integer.parseInt($value) and doesn't rely upon the #set having been called prior to performing the type conversion in the template.