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?
#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() )