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?

7 Answers 7

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());
5
  • 2
    im not able to use $numberTool, it simply prints numberTool.format($val,"#0.00"), do I need to include anything? Jan 11, 2012 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. Jan 11, 2012 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 6, 2012 at 8: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, 2016 at 14:13
  • 1
    @Vazdim not if velocity is properly secured. Jun 2, 2016 at 14:55
24
#set($String = "abc")
$String.format("%.2f", $val)

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

1
  • 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, 2015 at 4:42
2

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

1
  • This should be the answer! Dec 21, 2021 at 16:25
2

Use the MathTool from the VelocityTools project.

$math.roundTo(2, $val)
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)
2
  • 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, and its DateTimeFormatter.
    – Ole V.V.
    Apr 25, 2021 at 5: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. Apr 26, 2021 at 5:49
0

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.