RE: [xsl] Calculations involving measurements with units

Subject: RE: [xsl] Calculations involving measurements with units
From: "Ragulf Pickaxe" <jawxml@xxxxxxxxxxx>
Date: Fri, 02 Jan 2004 07:56:47 +0000
Hello Paul,

<xsl:variable name="upper-margin" select="number($page-height) / 3.75"/>

The number function returns NaN when the string cannot be expressed as a number - therefore this goes wrong.

If you know the units beforehand (i.e. always mm), then you can do:
<xsl:variable name="upper-margin" select="concat(number(translate($page-height, 'm', '')) / 3.75, 'mm')"/>
which throws away the m's. Then appends mm to the answer.


If you do not know beforehand the units, but need them from the string, then you can do a recursive solution taking one letter at a time, checking if it is a number. If it is not a number, you print out the units.

For example:
<xsl:variable name="Unit">
 <xsl:call-template name="TakeOutUnit">
   <xsl:with-param name="IsNumber" select="$page-height"/>
 </xsl:call-template>
</xsl:variable>

<xsl:variable name="upper-margin" select="concat(number(translate($page-height, 'abcdefghijklmnopqrstuvwxyz', '')) / 3.75, $Unit)"/>
<!-- Assuming that the units can only be in small letters -->


<xsl:template name="TakeOutUnit">
<xsl:param name="IsNumber"/>
<xsl:xhoose>
<xsl:when test="number(substring($IsNumber, 1, 1))!=NaN">
<xsl:call-template name="TakeOutUnit">
<xsl:with-param name="IsNumber" select="substring($IsNumber, 2, (1 div 0))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$IsNumber"/>
<!-- We assume that when the first character is not a number, then we have the unit -->
</xsl:otherwise>
</xsl:choose>
</xsl:template>



Hope this helps,


Regards,
Ragulf :)

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail



XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list



Current Thread