Saad Pervez
Saad Pervez

Reputation: 99

Rounding off to nearest 0.5 in matlab

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

Upvotes: 9

Views: 20129

Answers (3)

George Aprilis
George Aprilis

Reputation: 1200

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;

Upvotes: 17

PaxRomana99
PaxRomana99

Reputation: 574

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

Upvotes: 1

wakjah
wakjah

Reputation: 4551

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.

Upvotes: 3

Related Questions