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
.
Multiply by 1. A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.
Simply use g
instead of f
:
sprintf('%.15g', 3.0001)
ans =
3.0001
From doc sprintf
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 ')
do you mean this ?
sprintf('%.15g', 3.0001001)
==> 3.0001001
sprintf('%.15g', 3.0001)
==> 3.0001
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With