Say I want to print two numbers
1.755
1.234e-5
For the former, I would write
fprintf('%.3f', 1.755)
and for the latter
fprintf('%.3e', 1.234e-5)
Clearly, the first formatspec does not make sense for 1.234e-5 as it would be printed as 0.000
Is there a way to let matlab deduce an "optimal" best formatspec based on the value to be printed or must this be hardcoded by if-statements?
You probably want %.4g
. The format specification %g
is defined in the documentation as
The more compact of
%e
or%f
, with no trailing zeros (Use a precision operator to specify the number of significant digits.)
Note that, as indicated, with %g
the specified precision refers to the number of significant digits (whereas with %f
or %e
it would be the amount of digits to the right of the decimal point).