How do I use a user input for a desired number of decimal places in an fprintf or similar statement? The instructions are to use the user's input to display or print the correct number of decimal places once calculations are performed. Thanks!

I have tried using something like this to no avail:
fprintf('# Negative:\t\t\t\t\t%0.%f',decimal,neg)
Perhaps I need an sprintf statement or disp after the '# Negative' string? Any suggestions are most appreciated.

4 Comments

You should read this article carefully:
https://www.mathworks.com/help/matlab/ref/fprintf.html
Does this article explain how to use floating point as a variable rather than hard coding the outputs? I'm very familiar with how to do that in general but am experimenting with trying to use the '%f' as a variable somehow. Is it possible with an fprintf statement? I missed that if the information is in the article. I'll look again, thank you.
According to the fprintf documentation: "The precision operator can be a number, or an asterisk (*) to refer to an argument."
"Example: The input arguments ('%6.4f', pi) are equivalent to ('%*.*f', 6, 4, pi)."
It works, try it:
>> fprintf('%.*f\n', 5, pi)
3.14159
Ahh, I missed that the first time around. Thanks very much for your help!

Sign in to comment.

More Answers (0)

Categories

Find more on Scripts 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!