Welcome to our detailed guide on XSLT Decimal-Format! This tutorial is designed for both beginners and intermediate learners, aiming to help you understand and apply this powerful feature in your XML projects.
XSLT Decimal-Format is a feature that allows you to format numerical values in an XML document according to specific rules. It's particularly useful when you want to control the presentation of numbers, making them more readable and consistent.
<xsl:format-number value="number" decimal-format="format"/>value: The numerical value you want to format.decimal-format: The formatting rule for the number.XSLT provides predefined decimal formats like short, medium, and long. However, you can also create your own custom decimal-format.
Let's create a custom decimal-format that formats numbers with 2 decimal places and a comma as a thousand separator:
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="number">
<xsl:value-of select="format-number(., '0.##', 'en-US')"/>
</xsl:template>Now, let's use this custom decimal-format to format a number:
<xsl:format-number value="3.14159" decimal-format="custom"/>Output: 3.14
You can round numbers using the round attribute in the decimal-format:
<xsl:format-number value="3.14159" decimal-format="round(2)"/>Output: 3.14
For currency formatting, you can use the currency attribute:
<xsl:format-number value="12345.67" decimal-format="currency"/>Output: $12,345.67
Let's use XSLT Decimal-Format to display a product list with prices formatted as currency:
XML Data:
<products>
<product id="1" price="12.99">
<name>Product 1</name>
</product>
<product id="2" price="34.56">
<name>Product 2</name>
</product>
</products>XSLT:
<xsl:template match="products">
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<xsl:apply-templates select="product"/>
</tbody>
</table>
</xsl:template>
<xsl:template match="product">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="format-number(price, 'currency')"/></td>
</tr>
</xsl:template>Output:
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Product 1</td>
<td>$12.99</td>
</tr>
<tr>
<td>Product 2</td>
<td>$34.56</td>
</tr>
</tbody>
</table>What is the purpose of XSLT Decimal-Format?
How do you create a custom decimal-format in XSLT?