-2

Possible Duplicate:
Avoid trailing zeroes in printf()

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main(void)
    {
      FILE *file;
      double n;  
      file = fopen("fp.source", "r");
      while(!feof(file)) {
        fscanf(file, "%lf", &n);
        printf("Next double:\"%lf\"\n", n); 
    }
    fclose(file);
    return 0;
    }

Hi I am trying to scan for floating point numbers and I have gotten it to work, but I get trailing zeroes that I don't want. Is there a way to avoid this? For example, the current output I get is: Next double:"11.540000"

When in reality I would like: Next double:"11.54"

Community
  • 1
  • 1
DLR
  • 187
  • 3
  • 15

3 Answers3

5

That's not a problem with scanning. That is a problem with printf formatting.

From the documentation (emphasis mine):

f, F

The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification. If the precision is missing, it shall be taken as 6; if the precision is explicitly zero and no '#' flag is present, no radix character shall appear. If a radix character appears, at least one digit appears before it. The low-order digit shall be rounded in an implementation-defined manner.

You probably want %g (again, emphasis mine):

g, G

The double argument shall be converted in the style f or e (or in the style F or E in the case of a G conversion specifier), with the precision specifying the number of significant digits. If an explicit precision is zero, it shall be taken as 1. The style used depends on the value converted; style e (or E ) shall be used only if the exponent resulting from such a conversion is less than -4 or greater than or equal to the precision. Trailing zeros shall be removed from the fractional portion of the result; a radix character shall appear only if it is followed by a digit or a '#' flag is present.

user7116
  • 63,008
  • 17
  • 141
  • 172
3

Is there a way to avoid this?

Yes, just format the output correctly:

printf("Next double:\"%.0lf\"\n", n);

The .0 in the printf format string indicates that you don't want to print any digits after the decimal point. You can change the 0 to some other value if you want one, two, three or more digits after the decimal.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • If I were to use printf("Next double:\"%.0lf\"\n", n); it gets rid of numbers that need to be displayed, for example, i had 12.54 and it displayed 12, I need the .54 but not the 5 zeros after it. – DLR Jan 28 '13 at 19:23
  • The g/G specifier that @sixlettervariables points out looks like it'd do the trick. – Caleb Jan 28 '13 at 19:26
2

Try this.

printf("Next double:\"%l.0f\"\n", n); 

Here's a good reference for string format specifiers.

http://www.cplusplus.com/reference/cstdio/printf/

Jeff Wolski
  • 6,332
  • 6
  • 37
  • 69