I have a number like this:
2.32166873546944
I want to take only four numbers after the decimal point and without rounding, that is, I only want:
2.3216
How do I do this in Matlab ?
I tried several times to get the desired result but I was unable to do so. Please help me....
round
From the documentation (emphasis added),
Y = round(X)
rounds each element ofX
to the nearest integer. In the case of a tie, where an element has a fractional part of0.5
(within roundoff error) in decimal, theround
function rounds away from zero to the nearest integer with larger magnitude.
Thus, truncating to n
decimal figures can be achieved by reducing the absolute value of the number by 0.5*10^-n
and then applying round
:
n = 4;
x = 2.32166873546944;
y = round(x-sign(x)*0.5*10^-n, n);
fix
From the documentation (emphasis added),
Y = fix(X)
rounds each element of X to the nearest integer toward zero.
Thus, it suffices to multiply by 10^n
, apply fix
, and then divide by 10^n
:
n = 4;
x = 2.32166873546944;
y = fix(x*10^n)/10^n;