Reputation: 1659
I trying to implement the round function present in MatLab without using round or roundn. This is simply as a practice for an interview. My thinking process was as so: I know I would need to use the functions floor and ceil. I figured let me not jump into code without having the basics down first, and so here is my thought of the prototype, function x = f(z, d), where z is the number to be rounded and d is the number of digits.
Upvotes: 0
Views: 381
Reputation: 4558
This kind of problems can and is often (maybe too often sometimes) solved by some clever solution. This problem can for example be solved by adding the marginal to the number and then use floor.
function y = myround(x, n)
dec = (10^n);
y = floor(x*dec+0.5);
y = y/dec;
So if the decimal at position n+1
is 0.5 or larger floor will add one to the n:th decimal.
EDIT
This can be done with the 2 argument round
.
round(123.456,2)
ans =
123.4600
Upvotes: 1