cancel
Showing results for
Did you mean:

## Round of in KDB

New Contributor
Hi All,

Here is the information i want to share,

To round of up to any decimal place,Use below formula

Formula ---->  n*floor 0.5+m*AnyFloatValue

Eg.
1) One decimal place:

n = 1/10 = 0.1
m = 1*10 = 10

Expression Example ---->  0.1*floor 0.5+10*34.45
Output -----> 34.5f

2) Two decimal place:

n = 1/100 = 0.01
m = 1*100 = 100

Expression Example ---->  0.01*floor 0.5+100*34.456
Output -----> 34.46f
3 REPLIES 3
New Contributor II
you can find this functionality in the '.util.rnd' function provided in the code that accompanies "Q Tips: Fast, Scalable and Maintainable Kdb+": http://q-tips.net

https://github.com/psaris/qtips/blob/master/util.q

.util.rnd:{x*"j"\$y%x}

q).util.rnd[.1]34.45
34.5
q).util.rnd[.01]34.456
34.46

note: you can cast the number instead of adding .5 and taking the floor

New Contributor

If you need to be as accurate as possible, I'd suggest using division
rather than multiplication after the casting:

q)rnd:{x*"j"\$y%x}
q)rnd2:{("j"\$x*y)%x}
q)0=1.4-rnd[0.1;1.41]
0b
q)0=1.4-rnd2[10;1.41]
1b
New Contributor II
be careful when relying on exact comparisons with floats. a slight change to the inputs, might have unexpected results.

q)rnd2[10;4.1]
4.0999999999999996
q)rnd2[10;1#4.1]
,4.1000000000000005

q optimizes division of a vector by scalar. it first taking the reciprocal of the scalar and then multiplies.

q)41%10
4.0999999999999996
q)enlist[41]%10
,4.1000000000000005
q)41*1%10
4.1000000000000005

if you need exact values, it is better to store (and round) your data as integers