Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have sprintf to ignore trailing zeros

Tags:

printf

matlab

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.

like image 749
CitizenInsane Avatar asked Jul 10 '14 09:07

CitizenInsane


People also ask

How do you get rid of trailing zeros?

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.


2 Answers

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 ')
like image 163
RTL Avatar answered Oct 07 '22 01:10

RTL


do you mean this ?

sprintf('%.15g', 3.0001001)
==> 3.0001001
sprintf('%.15g', 3.0001)
==> 3.0001
like image 35
Ghislain Bugnicourt Avatar answered Oct 07 '22 02:10

Ghislain Bugnicourt