Formatting Text and Numbers

XSLT and XPath define a small set of functions to manipulate text and numbers. These allow you to concatenate strings, extract substrings, determine the length of a string, and perform other similar tasks. While these features do not approach the capabilities offered by a programming language like Java, they do allow for some of the most common string manipulation tasks.

Number Formatting

The format-number( ) function is provided by XSLT to convert numbers such as 123 into formatted numbers such as $123.00. The function takes the following form:

string format-number(number, string, string?)

The first parameter is the number to format, the second is a format string, and the third (optional) is the name of an <xsl:decimal-format> element. We will cover only the first two parameters in this book. Interestingly enough, the behavior of the format-number( ) function is defined by the JDK 1.1.x version of the java.text.DecimalFormat class. For complete information on the syntax of the second argument, refer to the JavaDocs for JDK 1.1.x.

Outputting currencies is a common use for the format-number( ) function. The pattern $#,##0.00 can properly format a number into just about any U.S. currency. Table 3-2 demonstrates several possible inputs and results for this pattern.

Table 3-2. Formatting currencies using $#,##0.00















The XSLT code to utilize this function ...

Get Java and XSLT now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.