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
do you mean this ?
sprintf('%.15g', 3.0001001)
==> 3.0001001
sprintf('%.15g', 3.0001)
==> 3.0001
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 ')