Important Notes

Number Format

Most methods in this tool return numbers wrapped as Double, which automatically render the decimal places, even for whole numbers. For example, the call $math.add(1, 2).toString() returns “3.0” rather than just “3”.

Parameters

With the exception of the methods listed below, all arguments supplied to all methods must be numbers. Integer arguments will be automatically converted to floating point numbers when supplied as arguments.

Methods accepting arguments other than numbers:

Method

Parameter Type(s)

Example

getAverage()

A list or collection containing only numbers.

$math.getAverage( [ 1, 2, 3 ] )

getTotal()

A list or collection containing only numbers.

$math.getTotal( [ 1, 2, 3 ] )

getRandom()

Does not take any arguments.

getRandom()

toDouble()

Either a number or a string containing a numeric format.

$math.toDouble( 5 )$math.toDouble( "5.6" )

toInteger()

Either a number or a string containing a numeric format.

$math.toInteger( 5.6 )$math.toInteger( "5" )

Math in Velocity

If you are performing only simple mathematical operations, you may be able to perform them without using the MathTool. Velocity supports simple math through the use of the #set() directive, including addition, subtraction, multiplication, division and modulus. The following table shows how to use #set directive mathematical operations, in comparison to using the MathTool:

Operator

MathTool

Velocity

Addition

#set($result = $math.add($value1, 1))

#set($result = $value1 + 1)

Subtraction

#set($result = $math.sub($value1, 2))

#set($result = $value1 - 2)

Multiplication

#set($result = $math.mul($value1, 3))

#set($result = $value1 * 3)

Division

#set($result = $math.div($value1, 4))

#set($result = $value1 / 4)

Modulus

#set($result = $math.mod($value1, 5))

#set($result = $value1 % 5)

Note: The Velocity #set directive can perform mathematical operations on both integers and floating point numbers. However operations on floating point numbers are not precise, and may contain errors in far decomal places, so if calculation accuracy is important, you should use the MathTool instead of Velocity.