Why not simply return trunc(val / 1000);
return trunc(val / 1000);
I still suspect that you don't understand hysteresis and running average