Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading