How to have sprintf to ignore trailing zeros
matlab, printf
Solution
Simply use `g` instead of `f`:
sprintf('%.15g', 3.0001)
ans =
3.0001
From `doc sprintf`
- %g The more compact form of %e or %f with no trailing zeros
The above method fails for numbers lower than 0.0001 (1e-4), in which case an alternative solution is to use %f and then `regexprep` here it replaces one more more zeros followed by a space with a space:
str = sprintf('%.15f ',mat);
str = regexprep(str,'[0]+ ',' ')
This method also has an issue with numbers lower than 5e-16 (such that there are only zeros for 15 digits to the right of the decimal point) having these significant digits removed.
To solve this instead of blindly replacing zeros, we can replace a digit in the range 1-9 followed by one or more zeros and then a space with that digit followed by a space:
str = sprintf('%.15f ',mat);
str=regexprep(str,'([1-9])[0]+ ','$1 ')
Problem
I want to convert a number to a string with at most 15 digits to the right of the decimal point. By at most i mean that if last digits are all zeros it is useless to print them. For instance: ``` sprintf('%.15f', 3.0001) ==> '3.000100000000000' ``` So far so good, but here as all trailing digits are all zeros, I would have prefered: ``` ==> '3.0001' ``` Is there a simple way to do it with `sprintf` format specifiers or should I manually post-process output to remove trailing zeros ? NB: I'm working with matlab in case there would be any other aternative to `sprintf`.