如何在 xquery 中格式化小数? [英] How can I format a decimal in xquery?
问题描述
我正在尝试在 XQuery 中格式化小数.小数是货币,所以格式应该是,###.##
.
I'm trying to format decimals in XQuery. The decimals are currency, so the format should be ,###.##
.
例如:
5573652.23
应该是 5,573,652.23
和
352769
应该是 352,769
(或者 352,769.00
如果它更容易/更干净)
352769
should be 352,769
(or 352,769.00
if it's easier/cleaner)
现在我正在使用 http://www.xqueryhacker.com/2009/09/format-number-in-xquery/,但我不能使用小数:
Right now I'm using this function from http://www.xqueryhacker.com/2009/09/format-number-in-xquery/, but I can't use decimals 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))
)
};
我的处理器使用 Saxon 9HE.
I'm using Saxon 9HE for my processor.
任何帮助将不胜感激.
----- 更新 -----
根据 Dimitre 的回答,我修改了函数以保存小数部分并将其添加到返回字符串的末尾.
Based on Dimitre's answer, I modified the function to save the decimal portion and add it to the end of the return string.
新功能
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 ()
)
};
推荐答案
使用:
let $n := 5573652.23
return
concat(local:format-int(xs:int(floor($n))),
'.',
substring(string($n - floor($n)), 3)
)
这会产生完全想要的正确结果:
5,573,652.23
这篇关于如何在 xquery 中格式化小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!