XSLT formatting numbers, insert '-' after

2019-07-26 07:35发布

问题:

I have a number that's 27 digits long, I need to format for readability purposes as below :

Input : 999967799857791961574987365

Expected output : 999-9677-9985-7791-9615-7498-7365

So in words, Starting from the right most, I need to insert a '-' after every 4 digits.

I have been using

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

but it doesn't work at all.

Any help or pointers would be great..Cheers

回答1:

The reason you can't just pass in the format string as you did and have it work is that the characters in the format string all have a special significance. The "-" is understood as the minus sign, not as a grouping separator. To make it work, you have to define a format using xsl:decimal-format and reference it using the optional third argument to format-number. Here's a complete stylesheet you can call on any XML file to illustrate:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:output method="text"/>
  <xsl:decimal-format name="dashes" grouping-separator="-"/>
  <xsl:template match="/">
    <xsl:value-of select="format-number(999967799857791961574987365,
                                        '-####', 'dashes')"/>
    <xsl:text>&#x0A;</xsl:text>
  </xsl:template>
</xsl:stylesheet>


回答2:

This seems like a hack to me, but you could try:

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

This worked in XSLT 1.0 and 2.0 for me.

Note: $ID must be an integer. You may need to use xs:integer($ID) (which may require a 2.0 processor).


Answer to comment:

Try this template instead:

<xsl:template name="ReceiptId">
    <xsl:param name="RECEIPT_ID_UNFORMATTED"/>
    <xsl:variable name="RECEIPT_ID_FORMATTED" select="translate(format-number(xs:integer($RECEIPT_ID_UNFORMATTED),',####'),',','-')"/>
    <div class="line">
        <xsl:value-of select="concat($RECEIPT_ID_PREFIX,&quot; &quot;,$RECEIPT_ID_FORMATTED)"/>
    </div>
</xsl:template>

Don't forget to declare the xs namespace in the xsl:stylesheet (xmlns:xs="http://www.w3.org/2001/XMLSchema") so you can use xs:integer()