How to convert string into integer in the Velocity template?

后端 未结 4 1298
挽巷
挽巷 2020-12-29 01:37

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条回答
  •  别那么骄傲
    2020-12-29 02:01

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

提交回复
热议问题