XSLT Template: math absolute value - math-abs(x) Options

codeling Posts: 1089 Points: 4569
Posted: Wednesday, June 19, 2019 2:49:05 PM

The abs function is part of XPath version 2.0 and as that supported in XSLT 2.0 processors like Saxon, AltovaXML and XMLPrime. Microsoft's XSLT processors (MSXML, XslTransform, XslCompiledTransform) are all XSLT 1.0 processors that only support the functions defined in XPath 1.0 and XSLT 1.0.

The following template implements the cacluation of an absolute value:

<xsl:template name="math-abs">
     <xsl:param name="x"/>
     
     <xsl:choose>
          <xsl:when test="$x &lt; 0">
               <xsl:value-of select="$x * -1"/>
          </xsl:when>
          <xsl:otherwise>
               <xsl:value-of select="$x"/>
          </xsl:otherwise>
     </xsl:choose>
     
</xsl:template>
 

codeling Posts: 1089 Points: 4569
Posted: Wednesday, June 19, 2019 2:52:13 PM

The short one relies on the fact that the true always converts to the number 1 and false to the number 0.

<xsl:template name="math:abs">
     <xsl:param name="x"/>
     <xsl:value-of select="(1 - 2 *($x &lt; 0)) * $x"/>
</xsl:template>
Users browsing this topic
Guest