How can I format a decimal number in xquery?

I am trying to format decimals in XQuery. Decimals are the currency, so there should be a format ,###.##.

For instance:

5573652.23 it should be 5,573,652.23

and

352769should be 352,769(or 352,769.00if it's easier / cleaner)

Now I use this function from http://www.xqueryhacker.com/2009/09/format-number-in-xquery/ , but I can not use decimal numbers with it:

declare function local:format-int($i as xs:int) as xs:string
{
  let $input :=
    if ($i lt 0) then fn:substring(fn:string($i), 2)
    else fn:string($i)
  let $rev := fn:reverse(fn:string-to-codepoints(fn:string($input)))
  let $comma := fn:string-to-codepoints(',')

  let $chars :=
    for $c at $i in $rev
    return (
      $c,
      if ($i mod 3 eq 0 and fn:not($i eq count($rev)))
      then $comma else ()
    )

  return fn:concat(
    if ($i lt 0) then '-' else (),
    fn:codepoints-to-string(fn:reverse($chars))
  )
};

I am using Saxon 9HE for my processor.

Any help would be greatly appreciated.

----- UPDATE -----

Based on Dimitre's answer, I changed the function to save the decimal part and add it to the end of the returned string.

New feature

declare function local:format-dec($i as xs:decimal) as xs:string
{
  let $input := tokenize(string(abs($i)),'\.')[1]
  let $dec := substring(tokenize(string($i),'\.')[2],1,2)
  let $rev := reverse(string-to-codepoints(string($input)))
  let $comma := string-to-codepoints(',')

  let $chars :=
    for $c at $i in $rev
    return (
      $c,
      if ($i mod 3 eq 0 and not($i eq count($rev)))
      then $comma else ()
    )

  return concat(if ($i lt 0) then '-' else (),
                codepoints-to-string(reverse($chars)),
                if ($dec != '') then concat('.',$dec) else ()
                )
};
+5
2

let $n := 5573652.23
 return
      concat(local:format-int(xs:int(floor($n))),
             '.',
             substring(string($n - floor($n)), 3)
             )

, :

5,573,652.23
+3

?:

format-number(5573652.23,",###.##")

. , .

. (. ).

0

All Articles