how to use fprintf in matlab?

2 views (last 30 days)
David Louie Bedia
David Louie Bedia on 2 Nov 2020
Edited: Stephen23 on 2 Nov 2020
Hi everyone! I would like to ask the difference between this codes using the command fprintf in matlab.
> x = 3; y = 2.71; z = x*y;
> fprintf('%d items at $%.2f\nTot = $%5.2f\n',x,y,z)
and
> x = 3; y = 2.71; z = x*y;
> fprintf('%d items at $%d \nTot = $%d',x,y,z)
I tried this in matlab and got the same result. What is '$%.2f' and '$%5.2f'?
Thanks in advance!!

Answers (2)

Rik
Rik on 2 Nov 2020
The answer is in the documentation. The first digit in your formatspec specifies the maximum number of characters in your output. The number after the point notes the number of decimal that will be printed. The dollar symbol has no specific meaning here.

Stephen23
Stephen23 on 2 Nov 2020
Edited: Stephen23 on 2 Nov 2020
"I tried this in matlab and got the same result."
The fprintf documentation states that "If you specify a conversion that does not fit the data... MATLAB overrides the specified conversion, and uses %e", and this is exactly what you are doing: you specified an integer format with %d but the data has a non-zero fractional part and so fprintf uses %e instead, which for some values may give the same output as the %f format.
I strongly recommend that you do not rely on this behavior.
"What is '$%.2f' and '$%5.2f'?"
The dollar sign is literal, it is not part of the number format.
  • '%.2f' prints a value with two fractional digits (decimal places).
  • '%5.2f' prints a value with minimum five characters (padded with leading spaces if required) and two fractional digits (decimal places).
The documentation is the best place to search for this information.

Categories

Find more on Characters and Strings 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!