The real Van Gogh
The real Van Gogh

Reputation: 39

Xquery transform string to same number but with decimal dot

I am working with xQuery version 1.0 and I'm trying to transform a string of numbers to the same number but with a decimal dot. But here's my problem. The decimal dot should be placed according to a certain element value.

The message I'm trying to transform:

<AMOUNT
    <VALUE>34221</VALUE>
    <NUMOFDEC>1</NUMOFDEC>
    <SIGN>+</SIGN>
    <CURRENCY>EUR</CURRENCY>
    <DRCR>C</DRCR>
</AMOUNT>

What I'm trying to achieve:

<prefix:Rates
<prefix:Amount currency="EUR">3422.1</prefix:Amount>
</prefix:Rates>

What did I try:

<prefix:Rates>
    <prefix:Amount currency="{ data(AMOUNT/CURRENCY) }">{ ((data(AMOUNT/VALUE) div 10)) }</prefix:Amount>
</prefix:Rates>

The problem with the above transformation is that it's not dynamic. But as you can see there is an element <NUMOFDEC>1</NUMOFDEC>. Can I use that value in a certain formula to place the decimal dot according to this value?

EDIT (19th october 2022): As a another user mentioned, there is recursion. Let's take this recursion from user @Michael Kay:

declare function f:two-to-the($n as xs:integer) as xs:integer {
if ($n = 0) then 1 else 2 * f:two-to-the($n - 1)
};

So how will I be able to apply this to my situation?

Upvotes: 0

Views: 118

Answers (2)

The real Van Gogh
The real Van Gogh

Reputation: 39

So I found a solution with an if-else statement. Unfortunately as another user mentioned, the mat:pow fucntion is not supported by Xquery 1.0.

Solution:

<prefix:Amount>{ 
(for $decimal in (data(AMOUNT/NUMOFDEC))
return if ($decimal = '1')
       then ((data(AMOUNT/VALUE)) div 10)
       else if ($decimal = '2')
            then ((data(AMOUNT/VALUE)) div 100)
            else ($decimal = '3')
                 then ((data(AMOUNT/VALUE)) div 1000)
                 else ((data(AMOUNT/VALUE)) div 10000))
}</prefix:Amount>

Is it fully dynamic? no. But it will do the trick for now.

EDIT (19th october 2022): The following recursion works!:

declare function xf:ten-to-the($decimal as xs:integer) as xs:integer {
if ($decimal = 0) then 1 else 10 * xf:ten-to-the($decimal - 1)
};

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167706

(div math:pow(10, AMOUNT/NUMOFDEC)) might do but I don't recall whether XQuery 1 supports the math namespace mathematical functions, namespace is e.g. math="http://www.w3.org/2005/xpath-functions/math", it might depend on your XQuery processor, I guess.

Upvotes: 1

Related Questions