how to use fprintf in matlab?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!!
0 commentaires
Réponses (2)
Rik
le 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.
0 commentaires
Stephen23
le 2 Nov 2020
Modifié(e) : Stephen23
le 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!