how to use fprintf in matlab?

조회 수: 3 (최근 30일)
David Louie Bedia
David Louie Bedia 2020년 11월 2일
편집: Stephen23 2020년 11월 2일
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!!

답변 (2개)

Rik
Rik 2020년 11월 2일
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 2020년 11월 2일
편집: Stephen23 2020년 11월 2일
"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.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by