Re: [xsl] Numbers containing 'e+..' not recognised as numbers

Subject: Re: [xsl] Numbers containing 'e+..' not recognised as numbers
From: Dimitre Novatchev <dnovatchev@xxxxxxxxx>
Date: Mon, 4 Jul 2005 06:34:56 +1000
On 7/4/05, Drew McLellan <lists@xxxxxxxxxxxxxxxx> wrote:
> I'm using the MSXML2 processor form with an ASP script, trying to
> transform a source xml document to xhtml.
>
> The problem is that my source document contains elements with
> attributes whose values are numeric. Sometimes these values are
> expressed in a format such as "4.364976000000000e+002". The xsl
> processor doesn't recognise these as numbers, and so format-number()
> or any function that requires a number as input simply returns NaN.
>
> I've tried using the number() function to convert to a number, but
> this has been unsuccessful.
>
> I'd be extremely grateful if anyone could
>
> a) suggest a method to get these numbers recognised as numbers, or
> b) suggest the correct mathematical term for these 'e+..' numbers so
> I can search more effectively!
>
> I always sucked at mathematics :)


XPath 1.0 does not recognize numbers in scientific notation. XPath 2.0 does.

I'd therefore recommend using an XSLT 2.0 processor such as Saxon 8.4
or Saxon.NET to solve this problem.

Numbers in scientific notation could be converted to xs:double using
FXSL for XSLT 2.0 in the following way (note that any base -- not only
10 -- is supported):

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
 xmlns:xs="http://www.w3.org/2001/XMLSchema";
 xmlns:f="http://fxsl.sf.net/";
 exclude-result-prefixes="f xs">

 <xsl:import href="../f/func-iter.xsl"/>
 <xsl:import href="../f/func-Operators.xsl"/>


 <xsl:output omit-xml-declaration="yes"/>


  <xsl:template match="/">
    <xsl:sequence select=" "/>
  </xsl:template>

  <xsl:function name="f:scientific2double" as="xs:double">
    <xsl:param name="x" as="xs:string"/>
    <xsl:param name="b" as="xs:integer"/>

    <xsl:sequence select=
     "for $vTerm1 in xs:double(substring-before($x,'e')),
          $vPow in xs:integer(substring-after($x,'e')),
          $vBase in
              if($vPow ge 0)
                 then $b
                else 1 div $b
             return
                f:iter(abs($vPow), f:mult($vBase), $vTerm1)
     "/>
  </xsl:function>
</xsl:stylesheet>

Here I use the f:iter() function of FXSL and also a partial
application of its f:mult() wrapper around the XPath 2.0 op:numeric
+() operator.

The result of the transformation is the correct:

     436.49760000000003

If I have:

  f:scientific2double('4e+002', 8)

the result is:

    256


The above transformation can be translated to FXSL for XSLT 1.0 almost
mechanically, by using the "iter" template and currying a template
that implements multiplication.


Cheers,
Dimitre Novatchev.

Current Thread