How to format both left and right of the decimal place with sprintf?
30 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Darrian Low
le 7 Déc 2025 à 10:39
Commenté : Walter Roberson
le 7 Déc 2025 à 18:43
I have four numbers below:
- 964.155
- 9590.43
- 350.76
- 0.00
These numbers need to be re-formatted to the following:
- 0964.16 (rounded up from .155)
- 9590.43
- 0350.76
- 0000.00
I have tried using the following code but to but to no avail.
sprintf('%4.2f, the_number)
What do I need to change in my code?
0 commentaires
Réponse acceptée
Walter Roberson
le 7 Déc 2025 à 11:33
N = [964.155
9590.43
350.76
0.00];
fprintf('%07.2f\n', N)
0 commentaires
Plus de réponses (1)
Dyuman Joshi
le 7 Déc 2025 à 11:42
Modifié(e) : Dyuman Joshi
le 7 Déc 2025 à 11:44
Here's an approach -
y = [964.155
9590.43
350.76
0.00];
You'll have to manually round up, as sprintf() doesn't do that (See this thread - https://in.mathworks.com/matlabcentral/answers/24638-round-towards-even-in-sprintf)
z = sprintf('%07.2f\n', round(y, 2))
As you want a total of 7 characters to be displayed (4 before the decimal, 1 - the decimal itself and 2 after the decimal), if there aren't sufficient total characters, pad them with zero - Thus the '07' in the call.
1 commentaire
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!