KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ Decimal Places by Condition

  • Decimal Places by Condition

    Posted by k-mambo on May 2, 2022 at 12:00 am

    Table Example

     

    start_date                    val 
    ---------------------------------------- 
    2022.05.02D07:36:35.901000000 0.01 
    2022.05.02D07:36:36.341000000 0.0125 
    2022.05.02D07:36:36.756000000 0.01234568 
    2022.05.02D07:36:37.204000000 0.9999 
    2022.05.02D07:36:37.636000000 0.008

     

    Desired Result

     

    start_date                    val 
    ---------------------------------------- 
    2022.05.02D07:36:35.901000000 0.01 
    2022.05.02D07:36:36.341000000 0.013 
    2022.05.02D07:36:36.756000000 0.012 
    2022.05.02D07:36:37.204000000 1 
    2022.05.02D07:36:37.636000000 0.008

     

    I tried follows.

     

    @[meter;`val;.Q.f[3]'] 
    start_date                    val 
    ------------------------------------- 
    2022.05.02D07:36:35.901000000 "0.010" 
    2022.05.02D07:36:36.341000000 "0.013" 
    2022.05.02D07:36:36.756000000 "0.012" 
    2022.05.02D07:36:37.204000000 "1.000" 
    2022.05.02D07:36:37.636000000 "0.008"

     

    How do I create a function to represent the desired result?

    The P is set to zero.

    k-mambo replied 8 months, 1 week ago 2 Members · 1 Reply
  • 1 Reply
  • Laura

    Administrator
    May 2, 2022 at 12:00 am

     

    q)show val:.01 .0125 .01234568 .9999 .008 0.01 0.0125 0.01234568 0.9999 0.008 
    
    q).001*floor .5+1000*val 0.01 0.013 0.012 1 0.008

     

    More generally, as a function which takes number of decimal places as its left argument:

     

    q){%[;s]floor .5+y*s:10 xexp x}[3]val 
    0.01 0.013 0.012 1 0.008

     

    Slightly less obviously you can elide floor .5+ with a faster Cast:

     

    q){%[;s]"i"$y*s:10 xexp x}[3]val 
    0.01 0.013 0.012 1 0.008

     

Log in to reply.