This is the mail archive of the
xsl-list@mulberrytech.com
mailing list .
left zero pad digit string
- To: "'Xsl-List (E-mail)" <xsl-list at mulberrytech dot com>
- Subject: left zero pad digit string
- From: Joel Hughes <joel at redknee dot com>
- Date: Thu, 31 Aug 2000 12:18:40 -0400
- Reply-To: xsl-list at mulberrytech dot com
Padding a number:
Requirement: zero pad a digit string
Example: 456 --> 000456
Where the new string length is a passed parameter to the padding template.
I am attempting to left zero pad a number. Presently unable to get more
than 1 digit padding with my recursive padding template (below).
I desire the effect of chaining concat calls.
Code attached below.
Alternatives:
1. format-number() does not appear to be an option for two reasons: 1)
unable to specify the formatting with element or attribute values; 2) do not
believe it will left pad zeroes.
2. brute force, not in the xsl spirit.
<xsl:template name="format-batchnum">
<xsl:param name="batchnum" select="0"/>
<xsl:param name="numbatchdigit" select="1"/>
<!-- zero string - 64 zeroes -->
<xsl:variable name="zerostr"
select="string('000000000000000000000000000000000000000000000000000000000000
0000')"/>
<xsl:variable name="padsize" select="$numbatchdigit -
string-length($batchnum)"/>
<xsl:variable name="zeropad" select="substring($zerostr, 1, $padsize)"/>
<xsl:value-of select="concat($zeropad, $batchnum)"/>
</xsl:element>
Thanks for any suggestions.
Joel
Attached code:
<!-- in calling template -->
<!-- example data: nextstartbatchnum = 4020, numbatchdigit = 12 -->
<!-- desired result: 000000004020 (12 digits in total) -->
<xsl:call-template name="format-batchnum">
<xsl:with-param name="batchnum" select="nextstartbatchnum"/>
<xsl:with-param name="numbatchdigit" select="numbatchdigit"/>
</xsl:call-template>
<!-- left zero pad batchnumber to numbatchdigit size -->
<xsl:template name="format-batchnum">
<xsl:param name="batchnum" select="0"/>
<xsl:param name="numbatchdigit" select="1"/>
<xsl:variable name="padded-number">
<xsl:call-template name="pad-number">
<xsl:with-param name="number" select="$batchnum"/>
<xsl:with-param name="pad" select="$numbatchdigit -
string-length($batchnum)"/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="$padded-number"/>
</xsl:template>
<!-- recursive padding template -->
<!-- each call concat leading zero -->
<!-- basecase: pad = 0 -->
<xsl:template name="pad-number">
<xsl:param name="number" select="0"/>
<xsl:param name="pad" select="0"/>
<xsl:choose>
<xsl:when test="pad > 0">
<xsl:variable name="number">
<xsl:call-template name="pad-number">
<xsl:with-param name="number" select="$number"/>
<xsl:with-param name="pad" select="$pad -1"/>
</xsl:call-template>
</xsl:variable>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat('0', $number)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Joel Hughes
joel@redknee.com
ph: +1 905 625 8235
fax: + 1 906 625 6485
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list