2

XPath in XQuery: Fractional Digits

I have an output XSD that looks like this:

<xs:simpleType name="Money">
  <xs:restriction base="xs:decimal">
       <xs:fractionDigits value="2"/>
   </xs:restriction>
</xs:simpleType>

From this I use a statments

fn:sum($Accounts/in:IndividualAcct[in:AcctType = 'AttcRec']/in:balance * in:amount)

But my summation to a field defined witht the definition above appears as:

36745.770000000004

What I am looking for is only 2 fractional digits

So I am wondering, can I use something like a format-string or fn:string

If so, can I combine this with my previous fn:sum string listed above

What would that look like?

Thanks

user3192053
  • 107
  • 2
  • 4
  • 10
  • possible duplicate of [How can I format a decimal in xquery?](http://stackoverflow.com/questions/5838562/how-can-i-format-a-decimal-in-xquery) – JLRishe Jan 21 '15 at 21:29
  • also related: http://stackoverflow.com/questions/5887784/formatting-the-output-of-the-sum-function-in-xquery-xslt-xpath – Daniel Haley Jan 22 '15 at 19:59

1 Answers1

4

You did not specify whether you have support for XQuery 3.0. If so, fn:format-number($number, $picture) is what you're looking for:

format-number(36745.770000000004, '.00')

Result: 36745.77

As @MichaelKay proposed in the comments, an alternative which also works in XQuery 1.0 would be to use the round-half-to-even($number, $precision) to limit the precision to two decimal digits. The number will automatically be casted to a string if necessary:

round-half-to-even(36745.770000000004, 2)
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • Can you combine this with the fn:sum command, and what would that look like ? – user3192053 Jan 21 '15 at 22:03
  • You can use arbitrary expressions returning an integer as first parameter. Just put the whole function call in there, something like `format-numer(sum(...), '.00')`. Remember whether to use the `fn:` namespace prefix is a matter of style and debate (usually you can use it for both functions, or omit it). – Jens Erat Jan 21 '15 at 22:06
  • 1
    Note also, in XQuery 1.0 you could use `round-half-to-even(sum(...), 2)` – Michael Kay Jan 22 '15 at 09:51