Summation Problem / Error in XSLT 1.0

I have XML data and try to sum 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 be 0 , but it ends with -0.0000000000005684341886080801

Run it in Visual Studio and see for yourself. Why? . It happens?

+3
source share
3 answers

It seems your XSLT processor converts strings of decimal numbers to precision floating point numbers before the sum;

, -, :

<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>
+5

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

How about adding a round?

round(sum(values/value))
+1
source

Source: https://habr.com/ru/post/1724723/


All Articles