Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Numbers in Velocity Templates?

Tags:

java

velocity

I am getting a java object in my velocity template. The object has a double value which I want to format to 2 decimal places and display it in my template.

The class for which im getting an object is something like this

Class Price
{
double value;
String currency;
}

In my velocity template, im getting the value like this

$price.value

but I need to format it to 2 decimal places before displaying it.

I want to convert

23.59004 to 23.59

35.7 to 35.70

3.0 to 3.00

9 to 9.00

Please tell me how can I do it in velocity template? I searched a lot for this and found that I can use velocity tools, but there are no examples related to it? and can i use velocity tools in templates?

like image 888
Rajesh Pantula Avatar asked Jan 11 '12 13:01

Rajesh Pantula


People also ask

How do you add numbers in Velocity template?

You would typically do something like #set ($oldIndex = $number. toNumber($oldIndex)) if you have the NumberTool present in your context, for instance. And that's it, $oldIndex contains an integer! Please note that the Integer.

What is Velocity format?

Velocity is a server-side template language used by Confluence to render page content. Velocity allows Java objects to be called alongside standard HTML. If you are are writing a user macro or developing a plugin you may need to modify Velocity content.

How do you declare a variable in Velocity?

Depending on what is added to the Velocity Context (MagicDraw automatically adds its element to the Velocity Context) the variable can either be a local variable or a reference to a Java object. To declare a local variable inside a template, type: $ followed by a string beginning with a letter.


1 Answers

Velocity tools are expected to be used in Velocity templates; essentially they are objects added to the variables available in a template so that you can use $numberTool.format("#0.00", $val) or similar. If none of the available tools don't fit your needs, simply create a POJO and add it to the template.

To make it working you also should add the following maven dependency:

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
</dependency>

and write following code:

context.put("numberTool", new NumberTool());
like image 86
Tassos Bassoukos Avatar answered Oct 12 '22 02:10

Tassos Bassoukos