Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

Formatting Numbers

In XPath, arithmetic is done using floating point math which can make for long output (Figures 4.9 and 4.10). Fortunately, with the format-number function, you can easily control the output format of numbers.

x s l t
 <xsl:when test="height != 0">
  <xsl:value-of select=
    "height"/> feet<br />
  (<xsl:value-of select=
    "height * 0.3048"/> m)

Figure 4.9. In this excerpt, I am outputting the height in feet and then converting the height to meters for output as well.

Figure 4.10

Figure 4.10 Remember that arithmetic is done using floating point math which, as I said, can make for really ugly output.

To format numbers:

  1. Type format-number(.
  2. Then, type the expression which contains the number to be formatted.
  3. Next, type , ' (a comma, a space, and a single quote).
  4. Then, type 0 for each digit that should always appear, and # for each digit that should only appear when not zero. If desired, type . (a period), to separate the integer part of a number from the fractional part, and , (a comma), to separate groups of digits in the integer part.
  5. Finally, type ') (a single quote followed by a right parentheses) to complete the number pattern and the function (Figure 4.11).
    x s l t
     "(<em><xsl:value-of select=
        (height * 0.3048, '##0.0')"/> m
        </em>)"/> m)

    Figure 4.11. The number being formatted is the same as in Figure 4.10 above. Now it will be formatted with at least one digit to the left of the decimal point, (but numbers are never truncated to the left) and exactly one digit to the right of the decimal point.

    Figure 4.12

    Figure 4.12 Now, the numbers look much better without quite so many digits.

  • + Share This
  • 🔖 Save To Your Account