How do you chop a number to a specified number of significant digits, not round
36 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
1 Comment
Answers (2)
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
Star Strider
on 22 Aug 2019
The print functions (such as sprintf and fprintf) round the result, so it is necessary to create more than the necessary number of decimal places, then use indexing to return only the number of digits desired.
Example:
x = exp(1);
s = sprintf('%.15f',x) % Generate 15 Decimal Places
n = str2num(s(1:4)) % Choose First 4 Characters
produces:
n =
2.71
Note that:
p = str2num(sprintf('%.2f',x))
rounds to produce:
p =
2.72
Experiment to get the result you want.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!