xsl-list
[Top] [All Lists]

RE: sum() function giving strange result

2004-12-13 23:34:45
Hi,

The sum funciton is giving some strange result.

Xml :-
<documents>
  <value>10.11</value>
  <value>20.22</value>
  <value>30.33</value>
  <value>40.44</value>
  <value>50.55</value>
  <value>10.11</value>
  <value>20.22</value>
</documents>

XSL :-
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
      xmlns:exsl="urn:schemas-microsoft-com:xslt"
                extension-element-prefixes="exsl">

<xsl:variable name="SubTotals">
  <xsl:for-each  select="/documents/value">
    <value><xsl:value-of select="." /></value>
  </xsl:for-each>
</xsl:variable>

<xsl:template match="/">
    <xsl:apply-templates select="documents/value" />
</xsl:template>

<xsl:template match="value">
     <xsl:variable name="Position" select="position()" />
     <xsl:value-of 
select="sum(exsl:node-set($SubTotals)/value[position() 
&lt; $Position])" /><br />
</xsl:template>

</xsl:stylesheet>


The result :-
0
10.11
30.33
60.66
101.1
151.64999999999998
161.76

I am worried about the output 151.64999999999998. Why is it 
outputting this 
value?

Because XPath uses a floating-point numbers 
<http://www.w3.org/TR/xpath#numbers>.

I am expecting to be upto 2 decimal places or 1 decimal places.

Well I can mask it upto 2 decimal places but I do not have a 
liberty to do 
that.

How about 

  <xsl:variable name="SubTotals">
    <xsl:for-each  select="/documents/value">
      <value>
        <xsl:value-of select=". * 100" />
      </value>
    </xsl:for-each>
  </xsl:variable>
  ...
  <xsl:template match="value">
    <xsl:variable name="Position" select="position()" />
    <xsl:value-of select="sum(exsl:node-set($SubTotals)/value[position() &lt; 
$Position]) div 100" />
    <br />
  </xsl:template>

Seems to give the expecter result.

0
10.11
30.33
60.66
101.1
151.65
161.76

Cheers,

Jarno

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--