How to convert string into integer in the Velocity template?

感情迁移 提交于 2019-12-03 08:08:41

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/2156502/how-to-convert-string-into-integer-in-the-velocity-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!