How do you chop a number to a specified number of significant digits, not round
56 views (last 30 days)
Show older comments
Is there a way to chop a number in matlab? I dont want to round it, just chop it off after a number of significants.
like e = 2.71828 eRound=2.72 eChop=2.71
2 Comments
Answers (1)
Bruno Luong
on 22 Aug 2019
2 digits
fix(x*100)/100
4 Comments
Stephen23
on 22 Aug 2019
Edited: Stephen23
on 22 Aug 2019
What is the difference? Disregarding any possible floating-point effects, I do not see how these are different. According to Wikipedia these are the same: "round towards zero (or truncate, ..."
Indeed the standard definition of truncation is
I note that you highlighted the term "rounds" but did not define it: rounding does not only include rounding to integer and rounding half up, but is really a family of functions (which includes fix and floor and ceil). Without defining exactly which one you are referring to by "rounds", your critique is entirely lost on me...
Bruno Luong
on 22 Aug 2019
I also fail to see why the fix method is criticized. I run this code, it does not look like I get different result than Star's solution
a = 1000*randn(1,1e6);
for x=a
r1=fix(x*100)/100;
s = sprintf('%.15f',x);
i = find(s=='.');
r2 = str2num(s(1:i+2));
if r1~=r2
keyboard
end
end
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!