kdb+q

Function to Convert decimals to percentage in KDB


`pct:157.35686
func[`pct]
func::{[x]
    ?[x>1;x-100;100*x]}

The result should be as 57.35%

`pct:0.804892
func[`pct]
func::{[x]
    ?[x>1;x-100;100*x]}

The result should be as 80.48%


Solution

  • Your use of Vector Conditional ? suggests your argument might be a vector†.

    q){?[x>1;x-100;x*100]} 157.35686 0.804892
    57.35686 80.4892
    

    The specimen answers are rounded down to two decimal places.

    q).01 xbar {?[x>1;x-100;x*100]} 157.35686 0.804892
    57.35 80.48
    

    The specimen answers are suffixed with percentage signs: cast them to strings. Project Join onto "%" to derive unary ,[;"%"] which you can apply with each.

    q),[;"%"] each string .01 xbar {?[x>1;x-100;x*100]}157.35686 0.804892
    "57.35%"
    "80.48%"
    

    † For an atom argument use the ‘ternary conditional’ control structure Cond.

    q){$[x>1;x-100;x*100]}157.35686
    57.35686
    q){$[x>1;x-100;x*100]}0.804892
    80.4892
    

    Why? Because Vector Conditional is an operator and all three of its arguments are evaluated. That is, whatever the result of x>1, both x-100 and x*100 are evaluated. With Cond, either the second or third expression is evaluated; never both.

    In this example, the cost is of course negligible. In other cases the expressions in the second and third arguments could be expensive.