Tuesday, 9 April 2013

Remove leading zeros from a number

There are three methods to remove leading zeros (or any other character) from a number using XSLT.

Use the number() function

number(.) 

to return a string you can use 

string(number(.))

Use the format-number() function 

format-number(.,'#')

Use the replace() function 

replace(.,'^0+','')

Try it using the following XML:
<test>
    <number>0001</number>
    <number>0002</number>
    <number>0003</number>
    <number>0011</number>
    <number>0102</number>
    <number>1003</number>
</test>


and the following xslt template:

<xsl:template match="test">
  <number>
    <xsl:for-each select="number">
       <n><xsl:value-of select="number(.)"/></n>
    </xsl:for-each>
   </number>
   <replace>
     <xsl:for-each select="number">
      <n><xsl:value-of select="replace(.,'^0+','')" /></n>
     </xsl:for-each>
   </replace>
   <format>
     <xsl:for-each select="number">
       <n><xsl:value-of select="format-number(.,'#')"/></n>
     </xsl:for-each>
   </format>
</xsl:template> 

No comments:

Post a Comment