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

codeling 1181 - 5025
@2019-06-19 14:49:05

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:when test="$x &lt; 0">
               <xsl:value-of select="$x * -1"/>
               <xsl:value-of select="$x"/>

codeling 1181 - 5025
@2019-06-19 14:52:13

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"/>
Users browsing this topic