What is the proper format string for float?

49 vues (au cours des 30 derniers jours)
Mr M.
Mr M. le 26 Mai 2015
Commenté : Walter Roberson le 10 Juin 2015
I would like to print a float without unnecessary characters. 0.2, 1.25, 0.02, but in case of lot of digits, I would like to cut the last digits: 1.234 to 1.23 %f, %.2f is not good I think

Réponses (2)

Dasharath Gulvady
Dasharath Gulvady le 29 Mai 2015
If you are looking for a way to round off the decimal values, see the below thread:
  1 commentaire
Mr M.
Mr M. le 10 Juin 2015
The problem is that %.2f is not good for me, since I dont want to show unnecessary zeros! For example 0.50 instead of 0.5. But 0.45 should be 0.45

Connectez-vous pour commenter.


Guillaume
Guillaume le 10 Juin 2015
Modifié(e) : Guillaume le 10 Juin 2015
There is no formatting option that does exactly what you want. You could switch to using '%g' instead of '%f', this does not print trailing zeros, but the precision is then the number of significant digits instead of the number of digits after the decimal point. Furthermore '%g' switches to exponential notation if the magnitude of the number is too big or too small.
For the examples, you've given:
sprintf(n, '%.4g')
works
  1 commentaire
Walter Roberson
Walter Roberson le 10 Juin 2015
%.2g rather than %.4g for the posted requirements.

Connectez-vous pour commenter.

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!

Translated by