4

I have this XML data and try and make a sum of it using the XSLT snippet below.

Xml

<?xml version="1.0" encoding="utf-8"?>
<values>
    <value>159.14</value>
    <value>-2572.50</value>
    <value>-2572.50</value>
    <value>2572.50</value>
    <value>2572.50</value>
    <value>-159.14</value>
</values>

Xslt

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <xsl:value-of select="sum(values/value)"/>
</xsl:template>

</xsl:stylesheet>

In my world the value should then be 0 but it ends up being -0.0000000000005684341886080801

Run it in Visual Studio and see for yourself. Why? is this happening?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Riri
  • 11,501
  • 14
  • 63
  • 88
  • 1
    Just to add a little completeness to the solution given below below and answer your question of "Why?" Check out "What Every Computer Scientist should know about Floating-Point Arithmetic" http://docs.sun.com/source/806-3568/ncg_goldberg.html – LorenVS Dec 04 '09 at 10:10

3 Answers3

5

Seems your XSLT processor convert decimal numbers strings to float-point precision numbers before sum;

Well, you can always to use round function and divide by your desired precision or to use format-number function, if available:

<xsl:template match="/">
    <xsl:value-of select="round(sum(values/value)) div 100"/><br />
    <xsl:value-of select="format-number(sum(values/value), '0.00')"/>
</xsl:template>
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • 1
    @Riri: If you are surprised about this behavior, I think this: http://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-point-rounding-error and the linked page in the accepted answer is worth a read. – Tomalak Dec 04 '09 at 10:21
2

Try this

<xsl:value-of select="format-number(sum(values/value),'0.00')"/>
1

How about adding round?

round(sum(values/value))
YOU
  • 120,166
  • 34
  • 186
  • 219
  • Posted the same comment above, but it feels in place here as well. Just to add a little completeness to the solution given below below and answer your question of "Why?" Check out "What Every Computer Scientist should know about Floating-Point Arithmetic" http://docs.sun.com/source/806-3568/ncg%5Fgoldberg.html – LorenVS Dec 04 '09 at 10:12