I have a question about formatting the output of the sum()
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.
Here is an example input file:
<userTotals>
<user cost="138764.63" hours="1506.51"/>
<user cost="329555.76" hours="3577.85"/>
<user cost="213909.81" hours="2322.33"/>
<user cost="22684.85" hours="246.28"/>
<user cost="6147.42" hours="66.74"/>
<user cost="1269.27" hours="13.78"/>
<user cost="181.45" hours="1.97"/>
<user cost="755.30" hours="8.2"/>
</userTotals>
Here is an example stylesheet:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/userTotals">
<results>
<cost><xsl:value-of select="sum(user/@cost)"/></cost>
<hours><xsl:value-of select="sum(user/@hours)"/></hours>
<hours-formatted>
<xsl:value-of select="format-number(sum(user/@hours),'###.##')"/>
</hours-formatted>
</results>
</xsl:template>
</xsl:stylesheet>
Here is the output:
<results>
<cost>713268.49</cost>
<hours>7743.659999999999</hours>
<hours-formatted>7743.66</hours-开发者_运维知识库formatted>
</results>
Notice the output of <hours>
and <hours-formatted>
. The content of <hours>
is the unmodified/unformatted output of sum()
. The content of <hours-formatted>
is the way I want the number formatted in both the XSLT and the XQuery.
The problem is that in XQuery, format-number()
is not available. How can I format the results of sum()
the same way in both XSLT and XQuery so that the results will appear like <hours-formatted>
?
Will I need to create a function that takes the output of sum()
as a string and process the decimal myself? In this case I would need to round .659
to .66
. I'm hoping there is a better way to do this (maybe cast the results as a different type and then ??).
Thank you for any info/guidance you can provide.
Saxon-PE and upwards offers format-number() in XQuery as an extension function (or by enabling XQuery 3.0 support).
But you can probably achieve what you want using the round-half-to-even() function.
This XQuery expression:
let $sum := string(ceiling(sum(/*/user/@hours) * 100)),
$length := string-length($sum)
return
concat(
substring($sum, 1, $length - 2),
'.',
substring($sum, $length - 1)
)
Output:
7743.66
精彩评论