-1

I don't figure out how to tell printf to print a double with a variable precision.

Where is what I actually do :

int main(void)
{
    int digits = 4;

    printf("%0.*f\n", digits, 0.123456789);
    printf("%0.*f\n", digits, 5.9);

    return (0);
}

I actually have the variable precision with the * and the digits variable, but it still prints remaining 0 after the last number.

In order to illustrate my problem, here is what i get :

0.1234
5.9000

And here is what i want :

0.1234
5.9

Could you help me please?

Chris Prolls
  • 89
  • 12

1 Answers1

4

You need to use %g instead of %f:

#include <stdio.h>

int main(void)
{
    int digits = 4;
    printf("%0.*g\n", digits, 0.123456789);
    printf("%0.*g\n", digits, 5.9);

    return 0;
}

Output:

0.1235 
5.9

LIVE DEMO

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • I already tried this, but it doesn't works very well, if I test with digits = 29 I got this output : 1.2345678899999998900938180668 – Chris Prolls Jan 11 '17 at 14:28
  • 3
    @ChrisProlls that is because the exact number is `0.12345678899999999733605449137030518613755702972412109375`. This is the nearest `double` number to `0.123456789`. – mch Jan 11 '17 at 14:38
  • 2
    @ChrisProlls-- also note that a `double` does not have 29 digits of precision. – ad absurdum Jan 11 '17 at 14:41
  • @DavidBowling I know, but I don't want to let any bug or usable breach, this why I asked if it's possible to print the float with a maximum precision, without add more digits than the float have. – Chris Prolls Jan 11 '17 at 14:55
  • 1
    I thought that you asked to "print a double with a variable float precision." – ad absurdum Jan 11 '17 at 14:58
  • 3
    @ChrisProlls Little need to print a `double` with more than `DBL_DECIMAL_DIG` (typically 17) significant digits. [Ref](http://stackoverflow.com/q/16839658/2410359). – chux - Reinstate Monica Jan 11 '17 at 16:09
  • I wasn't aware of some behaviours that float and double shares. Here is a good document to understand floating point precision in computer programming, that every beginner should read > [link](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Chris Prolls Sep 28 '18 at 10:30