function y = rd(x,p)
% Number x is rounded to p-digit decimal precision & returned in y.
% p has to be an integer equal to 1 or larger.
% Result has a relative error of eps.
% K. Ming Leung, 02/07/04

if p<1
    error('p has to be larger than 1!');
end
if x~=0
    s = sign(x);
    x = abs(x);
    exp = fix(log10(x));
    mantissa = x*(10^(-exp));
    pow1 = 10^(p-1);
    n = round(mantissa*pow1);
    y = s*n*(10^(1-p+exp));
else
    y = 0;
end
