How to format a number in Velocity

A Formatter can be passed to the template and the number can be parsed using that formatter.

Syntax:

$formatter.format( $number )

Example:

The following example creates a template contenaing 2 variables, first the formatter with the name formatter, that corresponds to the locale of the user. Then the number to format that is in the number variable.

Create the following java file:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.Locale;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocitySimple6 {

    public static void main(String[] argv) {

	// Source directory
	String sourceDirectory = "V:/tmp/velocity/";

	// Create the velocity engine
	VelocityEngine ve = new VelocityEngine();

	ve.setProperty("resource.loader", "file");
	ve.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
	ve.setProperty("file.resource.loader.path", sourceDirectory);
	ve.setProperty("file.resource.loader.cache", true);
	ve.setProperty("file.resource.loader.modificationCheckInterval", "2");

	ve.init();

	// Get the template
	Template t = ve.getTemplate("example6.vm");

	// Create the
	VelocityContext context = new VelocityContext();
	context.put("formatter", NumberFormat.getNumberInstance(Locale.ENGLISH));

	final double doubleToFormat = 1000000.01;
	context.put("number", doubleToFormat);

	try {
	    // Create the output file
	    Writer out = new BufferedWriter(
		    new OutputStreamWriter(new FileOutputStream(new File(sourceDirectory + "example6.txt")), "UTF8"));

	    t.merge(context, out);

	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

}

Create the following template called example6.vm:

The unformatted number is:	$number

The formatted number is:	$formatter.format( $number )

The output will be:

The unformatted number is:	1000000.01

The formatted number is:	1,000,000.01

References:

Java 8
Velocity

Share this article:

Recent Comments