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?
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
You can use the following to convert string to int: CInt(String) for ints. CDec(String) for decimals.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With