title: Formatting the output of the sum() function in XQuery/XSLT/XPath
body: <p>I have a question about formatting the output of the <code>sum()</code> function in XQuery/XSLT/XPath. I have both an XSLT stylesheet and also an XQuery. I'm able to get the correct formatting in the XSLT, but not in the XQuery.</p>
  
  <p>Here is an example input file:</p>
  
  <pre><code>&lt;userTotals&gt;
    &lt;user cost="138764.63" hours="1506.51"/&gt;
    &lt;user cost="329555.76" hours="3577.85"/&gt;
    &lt;user cost="213909.81" hours="2322.33"/&gt;
    &lt;user cost="22684.85" hours="246.28"/&gt;
    &lt;user cost="6147.42" hours="66.74"/&gt;
    &lt;user cost="1269.27" hours="13.78"/&gt;
    &lt;user cost="181.45" hours="1.97"/&gt;
    &lt;user cost="755.30" hours="8.2"/&gt;
  &lt;/userTotals&gt;
  </code></pre>
  
  <p>Here is an example stylesheet:</p>
  
  <pre><code>&lt;xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    &lt;xsl:output indent="yes"/&gt;
    &lt;xsl:strip-space elements="*"/&gt;
  
    &lt;xsl:template match="/userTotals"&gt;
      &lt;results&gt;
        &lt;cost&gt;&lt;xsl:value-of select="sum(user/@cost)"/&gt;&lt;/cost&gt;
        &lt;hours&gt;&lt;xsl:value-of select="sum(user/@hours)"/&gt;&lt;/hours&gt;
        &lt;hours-formatted&gt;
          &lt;xsl:value-of select="format-number(sum(user/@hours),'###.##')"/&gt;
        &lt;/hours-formatted&gt;
      &lt;/results&gt;
    &lt;/xsl:template&gt;
  
  &lt;/xsl:stylesheet&gt;
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>&lt;results&gt;
     &lt;cost&gt;713268.49&lt;/cost&gt;
     &lt;hours&gt;7743.659999999999&lt;/hours&gt;
     &lt;hours-formatted&gt;7743.66&lt;/hours-formatted&gt;
  &lt;/results&gt;
  </code></pre>
  
  <p>Notice the output of <code>&lt;hours&gt;</code> and <code>&lt;hours-formatted&gt;</code>. The content of <code>&lt;hours&gt;</code> is the unmodified/unformatted output of <code>sum()</code>. The content of <code>&lt;hours-formatted&gt;</code> is the way I want the number formatted in both the XSLT and the XQuery. </p>
  
  <p>The problem is that in XQuery, <code>format-number()</code> is not available. How can I format the results of <code>sum()</code> the same way in both XSLT and XQuery so that the results will appear like <code>&lt;hours-formatted&gt;</code>?</p>
  
  <p>Will I need to create a function that takes the output of <code>sum()</code> as a string and process the decimal myself? In this case I would need to round <code>.659</code> to <code>.66</code>. I'm hoping there is a better way to do this (maybe cast the results as a different type and then ??).</p>
  
  <p>Thank you for any info/guidance you can provide.</p>