XSLT - Remove currency formatting and check if number, otherwise pass as string
I need to remove currency formatting from a string, but my problem i开发者_如何学Pythons that the field sometimes contains currency and sometimes it is a string of text. So it could be:
$20
123,000.00 $123,000.00 Hello World!As a single XPATH test if the string could be evaluated as a number and return boolean:
number(translate(.,translate(.,'0123456789.',''),''))
You could put it into a template like this to return either a parsed number or nothing:
<xsl:template name="getNumber">
<xsl:param name="stringVal" />
<!--remove all characters other than number and period, use the result in the outer replace to yield only numbers and period -->
<xsl:variable name="numVal" select="translate(.,translate(.,'0123456789.',''),'')" />
<xsl:choose>
<!--If what is left evaluates as a number, then it's a number! -->
<xsl:when test="number($numVal)">
<xsl:value-of select="$numVal"/>
</xsl:when>
<xsl:otherwise>
<!--Do nothing-->
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Call the template like this:
<xsl:call-template name="getNumber">
<xsl:with-param name="stringVal" select="." />
</xsl:call-template>
I think this is a cleaner answer:
<xsl:template name="getNumber">
<xsl:param name="p_stringVal" />
<xsl:value-of select="translate($p_stringVal,translate($p_stringVal,'0123456789.',''),'')" />
</xsl:template>
Call the template like this (where $input_value = '$555,555.55' for example):
<xsl:call-template name="getNumber">
<xsl:with-param name="p_stringVal" select="$input_value" />
</xsl:call-template>
精彩评论