How to convert string into integer in the Velocity template?

Viewed 61642

I have a Velocity template file which has the data from XML. I want to convert the string into integer type.

How can I do that?

4 Answers

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.

Nice and easy:

#set( $stringToCast = "0" )
$number.toNumber($stringToCast)

$number is the default key name for the NumberTool, but it can be override by specifying a different name in the configuration (for example $numberTool). You have to check what name for NumberTool is used in your Velocity environment.

toNumber method returns:

the object as a Number or null if no conversion is possible

If you want to have explicite an int variable, not a Number object, you can use the intValue method on the result. So the above code will looks like this:

#set( $stringToCast = "0" )
$number.toNumber($stringToCast).intValue()

Of course, you can assign the result to another variable (for example $intVal).

So the full code can look like this:

#set( $stringToCast = "0" )
#set( $intVal = $number.toNumber($stringToCast).intValue() )
Related