Search code examples
xsltpaddingnumber-formatting

Padding with spaces and number formatting XSLT 1.0


Im trying to reformat weight values to not have any decimal places and always have six characters. Ive managed to work out how to pad with zeros but i cant seem to make it work with spaces. Any ideas?

Input:

<Weight>1150.0</Weight>

xlst:

<Weight><xsl:value-of select="format-number(Weight,'######')"/></Weight>

Expected output:

<Weight>  1150</Weight>

Current Output:

<Weight>001150</Weight>

Solution

  • Here is one way:

    <xsl:variable name="int" select="round(Weight)"/>
    <xsl:value-of select="substring(concat('      ', $int), 1 + string-length($int))"/>
    

    If your processor supports it, you could use the EXSLT str:align() extension function:

    <xsl:value-of select="str:align(round(Weight), '      ', 'right')"/>
    

    Note that the two methods will behave differently when the integer has more than 6 digits.