Search code examples
xslt-2.0saxon

Saxon XSLT | Sum Function


Perhaps this was already asked but I haven't been able to locate any posts on this. We use Saxon (HE-9.5.1-2) and the function sum returns a rather unusual value. Sum of 196.30 and 1018.57 is 1214.87 while Saxon returns a value of 1214.8700000000001.

Here's the repro.

Any inputs are appreciated. Thanks.


Solution

  • Use the xs:decimal data type

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
        <xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes"/>
        <xsl:template match="root">
            <root>
                <xsl:value-of select="sum(item/xs:decimal(.))"/>
            </root>
        </xsl:template>
    </xsl:stylesheet>
    

    and you will get e.g. <root>1214.87</root>.

    The default number type is IEEE double (xs:double), the same as for instance the number type in JavaScript and for that you will find the same floating point imprecision:

    var n1 = 196.30;
    var n2 = 1018.57;
    
    var sum = n1 + n2;
    
    console.log(sum);

    And of course it is not Saxon specific, any compliant XSLT processor for your code will use double number precision and should give that result.