How to convert string into integer in the Velocity template?

59,747

Solution 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.

Solution 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.

Solution 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.

Share:
59,747

Related videos on Youtube

uma
Author by

uma

Updated on October 12, 2020

Comments

  • uma
    uma over 3 years

    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?

    • vicatcu
      vicatcu over 14 years
      you have an XSLT file that operates on an XML input document and you want to convert a field that is type xs:string into type xs:integer?
    • uma
      uma over 14 years
      yes i have the xml input doucument which has the string value and i want to convert into integer
  • adarshr
    adarshr about 12 years
    Thanks so much for this. I was breaking my head over why $obj.getById("23") works where as #set($id = "23") $obj.getById($id)) doesn't.
  • Jabda
    Jabda almost 8 years
    works for me if I set the variable first #set($int = $Integer.parseInt($intString) )