18

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?

Rajesh Pantula
  • 10,061
  • 9
  • 43
  • 52

7 Answers7

29

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());
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
  • 2
    im not able to use $numberTool, it simply prints numberTool.format($val,"#0.00"), do I need to include anything? – Rajesh Pantula Jan 11 '12 at 14:01
  • 1
    See 'org.apache.velocity.tools.generic.NumberTool'. If you are using the tools.xml configuration, just follow the javadoc; if not, create a new NumberTool and add it to the parameter map. – Tassos Bassoukos Jan 11 '12 at 14:21
  • 3
    gosh, I didn't check the javadocs and was pulling my hair on : $numberTool.format($val,"#0.00"). To anyone, the format is : $numberTool.format("#0.00", $val) – TJ- Mar 06 '12 at 08:04
  • 1
    BTW, if the tool is present in classpath, but it was not put in velocity context beforehand, it still can be used like this: `#set($numberTool=$anyPresentVar.class.forName('org.apache.velocity.tools.generic.NumberTool').newInstance())##` – Vadzim May 30 '16 at 14:13
  • 1
    @Vazdim not if velocity is properly secured. – Tassos Bassoukos Jun 02 '16 at 14:55
24
#set($String = "abc")
$String.format("%.2f", $val)

$val has to be Double or Float in this case...

dedek
  • 7,981
  • 3
  • 38
  • 68
  • 1
    Indeed, this response deserves many more +1. Although derived from the `"".someStringFunction()` idiom, it is less obvious in Velocity because immediate strings can't be used like that. Setting a variable for the purpose isn't elegant, but, again, a lot simpler than much of what else is out there... BTW, this also works for another common-yet-hard-to-do thing: the conversion of numeric type to string type, without formatting, e.g. `$myString.format("%d", $myNumeric)` – mjv Dec 19 '15 at 04:42
3

Use the MathTool from the VelocityTools project.

$math.roundTo(2, $val)
abahet
  • 10,355
  • 4
  • 32
  • 23
2

formatCurrency($value). This is good java velocity code to format a number to currency format.

1

Solution by just using the Java Formatters: (without additional libraries)

NumberFormat decimalFormat = new DecimalFormat("#.00");
velocityContext.put("decimalFormat", decimalFormat);

Int Number: $decimalFormat.format($obj.intNum)

And here is how the timestamp is formatted to human readable date.

DateFormat DATETIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
velocityContext.put("datetimeFormat", DATETIME_FORMAT);

Timestamp to Date: $datetimeFormat.format($obj.timestamp)
Maqbool Ahmed
  • 316
  • 2
  • 7
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Apr 25 '21 at 05:49
  • 1
    Totally agreed with you @OleV.V. - The idea here is to provide a means of having these formatters from JDK itself rather than having additional libraries. People can use whatever best suits them. – Maqbool Ahmed Apr 26 '21 at 05:49
0

$numberTool.format("#0.00", $val)

Rafael Sanches
  • 1,823
  • 21
  • 28
0

A better way to do things besides using $numberTool.format is to use one of the MessageFormat-based tool classes that do more than just numbers. For example, we use MessageTool which is Struts-specific, but you can use something similar like ResourceTool instead:

resources.properties
some.key=The price is currently {0,number,$#.##}

template.vm
<p>
  $msg.get('some.key', 'resources', [$price])
</p>

This way, you get the number in context and not just all by itself. In a non-English language, the number might be more appropriate to come to the left of the text, or in the middle, or whatever. This gives you much more flexibility than simply formatting the number all by itself.

Christopher Schultz
  • 20,221
  • 9
  • 60
  • 77