What is the code to round float to fixed decimal places after coma:
round float 1.3379 to 1.34 or 1.3, for example.
There isn’t a built in function to do this (that I can find in Squirrel docs at least)… but it’s easy to accomplish with a bit of math
The first thing we need to do is multiply the number by a factory of 10 (at the end of this we’ll divide it by the same value). If you want to round to one decimal place, you multiply it by 10, if you want to round to two multiply by 100, and so on…
function round(val, decimalPlaces) local f = math.pow(10, decimalPlaces) * 1.0; // we multiply by 1.0 to ensure it's a flaot local newVal = val * f;
At this point, we’ve turned 1.3379 into 13.379 (if we’re rounding to 1 decimal place) or 133.79 (if we’re rounding to 2 decimal places).
The next thing we do is add 0.5, and floor the value - the floor function turns a float into an int and ALWAYS rounds down… ie - floor(4.1) = 4 and floor(4.99999) = 4:
newVal = math.floor(newVal + 0.5);
For the one decimal point example, we have:
13.379 + 0.5 = 13.879
floor(13.879) = 13
For the two decimal point example, we have:
133.79 + 0.5 = 134.29
floor(134.29) = 134
Finally, we divide our result by the same factor of 10 as we originally multiplied it by:
newVal = (newVal * 1.0) / f;
For 1 decimal point:
13.0 / 10.0 = 1.3
For 2 decimal points:
134.0 / 100.0 = 1.34
All together, the round function looks like this:
`function round(val, decimalPoints) {
local f = math.pow(10, decimalPoints) * 1.0;
local newVal = val * f;
newVal = math.floor(newVal + 0.5)
newVal = (newVal * 1.0) / f;
return newVal;
}
server.log(round(1.3379, 0));
server.log(round(1.3379, 1));
server.log(round(1.3379, 2));`
Thanks! I’ll try.
Currently I use following to get 1 digit after come, but time after time I cannot trust ti result (currently I think so), but may be it is just ADC noise, my be I have write wrog piece of code:
y is float, for example y=53.05611
y=y.tointeger() + math.ceil((1 - (math.ceil(y) - y)) * 10)/10;
as result I get y=53.1.
@beardedinventor
Your code work excellent! Thanks!
Any plans to make this a standard squirrel function… as had to search how to do this and thankfully found this useful post.
Hope this will help you…
float f = 10.123456F;
float fc = (float)Math.Round(f * 100f) / 100f;
More info…Round a float value to 2 decimal places
Lee