Search code examples
xsltfloor

XSLT - Floor incorrect value


When I am doing a floor( 10000000 * 1.1158 ) the output is 11157999 instead of being 11158000. But when i try a floor( 11158000 ) it returns me the good value.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
format-number(floor(10000000 * 1.1158) div 10000000, '#.0000000') = <br/>
     <xsl:value-of select="format-number(floor(10000000 * 1.1158) div 10000000, '#.0000000')"/>
<br/><br/>
floor(10000000 * 1.1158) div 10000000 = <br/>
     <xsl:value-of select="floor(10000000 * 1.1158) div 10000000"/>
<br/><br/>
floor( 10000000 * 1.1158 ) =<br/>
     <xsl:value-of select="floor( 10000000 * 1.1158 )"/>
<br/><br/>
10000000 * 1.1158 = <br/>
     <xsl:value-of select="10000000 * 1.1158"/>
<br/><br/>
floor(11158000 =
<br/>
     <xsl:value-of select="floor(11158000)"/>
</body>
  </html>
</xsl:template>
</xsl:stylesheet>

Output:

format-number(floor(10000000 * 1.1158) div 10000000, '#.0000000') =
1.1157999

floor(10000000 * 1.1158) div 10000000 = 
1.1157999

floor( 10000000 * 1.1158 ) =
11157999

10000000 * 1.1158 = 
11158000

floor(11158000 = 
11158000

Solution

  • If you are using XSLT 1.0 then all arithmetic is double-precision floating point. This can't represent all decimal fractions exactly, so it uses an approximation. For example the nearest xs:double value to 1.1158 is probably something like 1.1157999999999. If you want exact decimal arithmetic, you'll need to use the xs:decimal data type in XSLT 2.0.