Cole MG
Cole MG

Reputation: 343

How do I cast a float to an integer datatype in KDB?

I have a table in KDB(Q) with a size column that is currently in float format. How do I cast the entire column from float to int, while truncating the decimal place?

Upvotes: 0

Views: 1747

Answers (2)

Eliot Robinson
Eliot Robinson

Reputation: 666

Another way of doing this is using the @ amend to update the column(s):

q)t:([]sym:500?`3;px:500?10f;size:500?100f)
q)3#t
sym px       size
---------------------
gdh 7.678514 95.25017
jlb 2.345028 42.09728
nln 5.553286 98.80532
q)t:@[t;`size;"i"$] / can also use `t to update t
q)3#t
sym px       size
-----------------
gdh 7.678514 95
jlb 2.345028 42
nln 5.553286 98

I think its also worth pointing out that floor/ceiling functions round numbers down/up respectively and works slightly faster than "i"$ in this case, however these functions cast the column to a long instead of an int:

q)meta@[t;`size;floor]
c   | t f a
----| -----
sym | s
px  | f
size| j

Upvotes: 2

Cmccarthy1
Cmccarthy1

Reputation: 388

You can do this by updating your table

q)tab:([]bid:1000?5f;price:1000?5f;size:1000?100f)
q)exec t from meta tab
"fff"
q)update "i"$size from `tab
`tab
q)exec t from meta tab
"ffi"

In the above the pertinent point is the application of "i"$ which is 'casting' the size column from a float to an integer

Upvotes: 3

Related Questions