How do you chop a number to a specified number of significant digits, not round

조회 수: 36 (최근 30일)
Dawn Walaitis
Dawn Walaitis 2019년 8월 22일
편집: Stephen23 2019년 8월 22일
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개)

Bruno Luong
Bruno Luong 2019년 8월 22일
2 digits
fix(x*100)/100
  댓글 수: 4
Stephen23
Stephen23 2019년 8월 22일
편집: Stephen23 2019년 8월 22일
"Note that by definition, fix rounds toward zero. It does not truncate."
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
which is exactly what Bruno Luong's answer is doing.
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
Bruno Luong 2019년 8월 22일
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
Star Strider 2019년 8월 22일
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.

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by