Skip to main content

Arithmetic Expressions

An arithmetic expression is a placeholder for its result. Whenever a number is explicitly expected (attributes of type int or float), the corresponding expression is automatically evaluated arithmetically. Its result is then implicitly cast to the appropriate input type.

This automatic evaluation means that you can write complex mathematical expressions directly in attribute values. For example, <for var="i" from="2 * 3" to="(10 + 5) / 3"> evaluates from to 6 and to to 5 (truncated to integer because the to attribute has type int).

All C-like arithmetic and bitwise operators as well as their respective precedences are applicable to arithmetic expressions. This includes addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and bitwise operations (&, |, ^, ~, <<, >>), as well as parentheses for grouping.

Number notation

Integer numbers can be specified in multiple bases:

BasePrefixExampleDecimal Equivalent
Decimal (base 10)none123123
Hexadecimal (base 16)0x0x1A26
Octal (base 8)001715
Binary (base 2)0b0b110113

Floating point numbers can be specified in decimal (base 10) notation or scientific E notation. Scientific notation uses the format <mantissa>e<exponent>, where the result equals mantissa x 10^exponent. For example, 1.5e3 equals 1500.0, and 2.5e-2 equals 0.025.

warning

The octal prefix 0 can cause unexpected results. If you write <for from="010">, the runtime interprets 010 as octal 10, which is decimal 8. Always use the explicit 0o or bare decimal notation to avoid this ambiguity.

Expression evaluation in command attributes

Arithmetic expressions are evaluated automatically wherever an attribute of type int or float is expected:

XML
<math:abs var="number">(0x12 - 19.5) * $number</math:abs>

In this example, 0x12 (hexadecimal 18) minus 19.5 equals -1.5, which is then multiplied by the value of $number. The math:abs command takes the absolute value of the result.

Inline arithmetic substitution

The $() syntax embeds arithmetic results directly into string context, even where an arithmetic type is not expected. This allows you to perform calculations inside <output> content, <set> values, and other string contexts:

XML
<set var="birthyear">1950</set>
<output>This person is $(2012 - $birthyear) years old!</output>
<!-- This person is 62 years old! -->

Inline arithmetic may be nested within array access, enabling computed indices:

XML
<array var="names">
<item>Bill Gates</item>
<item>Steve Jobs</item>
</array>

<output>$names[0] and $names[$(0 + 1)] are competitors!</output>
<!-- Bill Gates and Steve Jobs are competitors! -->

See also

  • eval — evaluating expressions and storing the result
  • cast — converting string values to numeric types