truncate decimal numbers in matlab?
Here's one method to truncate d
digits after the decimal.
val = 1.234567;
d = 4;
val_trunc = fix(val*10^d)/10^d
Result
val_trunc =
1.2345
If you know that val
is positive then floor()
will work in place of fix()
.
Yet another option:
x = -3.141592653;
x_trun = x - rem(x,0.0001)
x_trun =
-3.1415
Kudos to gnovice for the update.
In general, for n
decimal places:
x_trun = x - rem(x,10^-n)
Truncating is like rounding if you subtract 5
from the decimal after the last you want to keep.
So, to truncate x
to n
decimal figures use
round(x - sign(x)*.5/10^n, n)
(Thanks to @gnovice for noticing the need of sign(x)
in order to deal with negative numbers.)
For example,
format long
x = 3.141592653589793;
for n = 2:5
result = round(x - sign(x)*.5/10^n, n);
disp(result)
end
gives
3.140000000000000
3.141000000000000
3.141500000000000
3.141590000000000