Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string into integer in the Velocity template?

Tags:

velocity

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?

like image 211
uma Avatar asked Jan 28 '10 17:01

uma


People also ask

What command will convert strings to integers?

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.

Can you convert a string into a number?

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.

How do you convert a string to integer in Visual C#?

You can use the following to convert string to int: CInt(String) for ints. CDec(String) for decimals.


2 Answers

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.

like image 149
Quotidian Avatar answered Sep 17 '22 18:09

Quotidian


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.

like image 26
ATG Avatar answered Sep 19 '22 18:09

ATG