Decimal Places by Condition

https://learninghub.kx.com/forums/topic/decimal-places-by-condition

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.

 

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