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

23 visualizaciones (últimos 30 días)
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

Respuestas (2)

Bruno Luong
Bruno Luong el 22 de Ag. de 2019
2 digits
fix(x*100)/100
  4 comentarios
Stephen23
Stephen23 el 22 de Ag. de 2019
Editada: Stephen23 el 22 de Ag. de 2019
"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 el 22 de Ag. de 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

Iniciar sesión para comentar.


Star Strider
Star Strider el 22 de Ag. de 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.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by