How to convert string into integer in the Velocity template?

The problem with parseInt is that it throws an exception in case the string is not parseable. In case you have the NumberTool loaded into your context a better solution than parseInt is the following:

#set($intString = "009")
#set($Integer=$numberTool.toNumber($intString).intValue())

#if($Integer)
 ## ok
#else
 ## nok
#end

Sometimes the NumberTool is also loaded as $number.

However, a little drawback is, that the NumberTool simply parses the first number it finds and ignores the rest, so "123a" => 123.


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.


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.

Tags:

Velocity