This chapter is from the book

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.

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 Remember that arithmetic is done using floating point math which, as I said, can make for really ugly output.

To format numbers:

Type format-number(.

Then, type the expression which contains the number to be formatted.

Next, type , ' (a comma, a space, and a single quote).

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.

Finally, type ') (a single quote followed by a right parentheses) to complete the number pattern and the function (Figure 4.11).

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 Now, the numbers look much better without quite so many digits.

TIPS

Use #,##0.00 to output at least one digit in the number, with commas separating every three digits, and exactly two digits in the fractional
part of the number (as in dollars and cents: 269.40). With #,000.0#, numbers with tenths (but not hundredths) would have no final zero, for example: 269.4.

Negative numbers are preceded by a minus sign (–) by default. If you’d rather that they be surrounded by parentheses, add
;(0) after Step 4 above.