How can I round off a decimal to the nearest 0.5 in matlab? E.g. I want 16.625 to be rounded to 16.5
It's the same logic, the same question was made for C#
result = round(value*2)/2;
And to generalize, according to aardvarkk's suggestion, if you want to round to the closest accuracy acc
, for example acc = 0.5
:
acc = 0.5;
result = round(value/acc)*acc;
If you go the multiply by 2 - round - divide by 2 route, you may get some (very small) numerical errors. You can do it using mod
to avoid this:
x = 16.625;
dist = mod(x, 0.5);
floorVal = x - dist;
newVal = floorVal;
if dist >= 0.25, newVal = newVal + 0.5; end
You could do it in fewer steps, but here I have broken it up so you can see what each step does.
a=16.625;
b=floor(a);
if abs(a-b-0.5) <= 0.25
a=b+.5;
else
if a-b-0.5 < 0
a=b;
else
a=b+1;
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With