What is the proper format string for float?

조회 수: 48 (최근 30일)
Mr M.
Mr M. 2015년 5월 26일
댓글: Walter Roberson 2015년 6월 10일
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

답변 (2개)

Dasharath Gulvady
Dasharath Gulvady 2015년 5월 29일
If you are looking for a way to round off the decimal values, see the below thread:
  댓글 수: 1
Mr M.
Mr M. 2015년 6월 10일
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

댓글을 달려면 로그인하십시오.


Guillaume
Guillaume 2015년 6월 10일
편집: Guillaume 2015년 6월 10일
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
Walter Roberson
Walter Roberson 2015년 6월 10일
%.2g rather than %.4g for the posted requirements.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by