Search code examples
xmlxsltxhtmlxslt-2.0

Retain trailing zeros after multiplication XSLT


I have a problem in which I need to retain the trailing zeros after the mathematical computation.

For eg: 9854.32000 * 1 should return 9854.32000 instead of 9854.32. I tried using

<xsl:decimal-format name="test" decimal-separator="."/>

<xsl:value-of select="format-number(26825.8000 * 1, '#.000', 'test')"/>

But I would like to learn if there is a way for me to do this generically by counting the length of trailing zeros and append them to the result

Please advice


Solution

  • The picture string of format-number() can be calculated. Consider the following example:

    XML

    <input>
        <multiplicand>1</multiplicand>
        <multiplicand>2.0</multiplicand>
        <multiplicand>3.14</multiplicand>
        <multiplicand>4.000</multiplicand>
        <multiplicand>5.0000</multiplicand>
        <multiplicand>6.12345</multiplicand>
        <multiplicand>7.000000</multiplicand>
    </input>
    

    XSLT

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:param name="multiplier" select="2"/>
    
    <xsl:template match="/input">
        <output>
            <xsl:for-each select="multiplicand">
                <xsl:variable name="zeros" select="translate(substring-after(., '.'), '123456789', '000000000')" />
                <product>
                    <xsl:value-of select="format-number(. * $multiplier, concat('#.', $zeros))" />
                </product>
            </xsl:for-each>
        </output>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    <?xml version="1.0" encoding="UTF-8"?>
    <output>
       <product>2</product>
       <product>4.0</product>
       <product>6.28</product>
       <product>8.000</product>
       <product>10.0000</product>
       <product>12.24690</product>
       <product>14.000000</product>
    </output>