xslt

Make a Negative number Positive - XSLT


I was wondering whether there is a way to make a negative value, positive? Here is a snippet of my xslt document:

<NumberOfLinesAtRate>
    <xsl:value-of select="number(/xsales:Qty)" />
</NumberOfLinesAtRate>

The problem is, sometimes this Qty value may be negative, -1, -2 etc.. in my original XML document. Is there a way I can make this always be positive in my transformed document?


Solution

  • If you are using XSLT1.0 you can use this formula (I've left out the namespace for brevity)

    <xsl:value-of select="Qty * (Qty >= 0) - Qty * not(Qty >= 0)" />
    

    In XSLT2.0 there is a dedicated abs operator you can use

    <xsl:value-of select="abs(Qty)" />