Function to chop a decimal to a variable number of digits

조회 수: 14 (최근 30일)
Aleem Andrew
Aleem Andrew 2020년 10월 3일
댓글: Aleem Andrew 2020년 10월 3일
I wrote the following function to approximate a number using chopping arithmetic.
chop(5,4.333352312)
function output = chop(numdigits,float)
y = floor(log10(float)+1); %number of digits in the integer part
x = fix(numdigits - y);
fprintf("%.xf",float)
end
The function is meant to approximate a float using numdigits chopping arithmetic. Since that is a variable, the number of digits after the decimal point is unknown. The output in the above example should be 4.3333 but the output is 4e+00. Is there any alternate way to display a variable number of digits after the decimal point?

채택된 답변

Stephen23
Stephen23 2020년 10월 3일
편집: Stephen23 2020년 10월 3일
You can use an asterisk * to refer to an input of fprintf, so in your case all you need is:
fprintf("%.*f\n",x,float);
and tested:
>> chop(5,4.333352312)
4.3334
Of course if you want to return that string as an output argument you will need to use sprintf instead:
function s = chop(numdigits,float)
y = floor(log10(float)+1);
x = fix(numdigits - y);
s = sprintf("%.*f",x,float);
end

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 10월 3일
편집: Ameer Hamza 2020년 10월 3일
MATLAB does not recognize what does 'x' means inside fprintf() function call. Try the following code
chop(3,4.333352312)
function chop(numdigits,float)
y = floor(log10(float)+1); %number of digits in the integer part
fprintf(sprintf('%%%d.%df', numdigits+1, numdigits-y), float);
end

카테고리

Help CenterFile Exchange에서 Time Series에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by