web analytics

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

Options

codeling 1602 - 6666
@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: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>

@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"/>
</xsl:template>

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com