How to convert string into integer in the Velocity template?

后端 未结 4 1318
挽巷
挽巷 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:20

    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.

提交回复
热议问题