Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've had endless trouble with decimals in XSLT/XPath 1.0, often a combination of it representing decimals as floating-point numbers and it using half-even rounding (banker's rounding). Unfortunately, the <code>round(yournum*100) div 100</code> approach didn't work for me, due to floating-point imprecision. For example, multiplying 1.255 by 100 gives 125.49999999999999 (this isn't meant to be implementation dependent, as it's supposed to be IEEE 754, but I don't know if all implementations do adhere to that). When rounded, this then gives 125, rather than the desired 126.</p> <p>I've taken the following approach, which I think works (although this is always a tricky area so I won't declare too much confidence!). However, it depends on your XSLT engine supporting EXSLT extensions. It presumes you want to round to two decimal places.</p> <pre><code>&lt;func:function name="local:RoundHalfUp"&gt; &lt;xsl:param name="number"/&gt; &lt;xsl:choose&gt; &lt;xsl:when test="contains($number, '.')"&gt; &lt;xsl:variable name="decimal" select="estr:split($number, '.')[2]"/&gt; &lt;xsl:choose&gt; &lt;xsl:when test="string-length($decimal) &amp;gt; 2"&gt; &lt;func:result select="format-number(concat($number, '1'), '0.00')"/&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;func:result select="format-number($number, '0.00')"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;func:result select="format-number($number, '0.00')"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/func:function&gt; </code></pre> <p>which can be called like:</p> <pre><code>&lt;xsl:value-of select="local:RoundHalfUp(1.255)"/&gt; </code></pre> <p>The namespaces are:</p> <pre><code>xmlns:func="http://exslt.org/functions" xmlns:estr="http://exslt.org/strings" xmlns:local="http://www.acme.org/local_function" </code></pre> <p>It's important to note that the function <em>appends</em> a '1', not adds 0.001 or similar.</p> <p>Definately better to use XSLT 2.0 if it's an option (because it has a proper decimal type), but I know that's often not an option (from painful experience!).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload