cplusalex
cplusalex

Reputation: 83

Problem reading a double from file with 1 decimal place (C)

For some reason when I try to read in a double and print it out with this code, it prints out: "865955189279958860000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000"

    fscanf(inFile, "%.1lf", &value);
    printf("%.lf\n", value);

When I change the code to this:

    fscanf(inFile, "%lf", &value);
    printf("%.1lf\n", value);

I get the output I want. But obviously I want the double to be stored as 8.1 (for instance), rather than having to format when I print it.

Any help would be greatly appreciated!

Upvotes: 0

Views: 648

Answers (1)

the busybee
the busybee

Reputation: 12600

A double has always a certain number of significant decimal digits, for example IEEE 754 gives 15 to 17. So you can't limit stored values to an arbitrary number of decimal places, let alone the problem of decimal fractions represented by binary numbers. For example, there is no way to exactly store 6.1 in an IEEE-754-double.

Anyway, you might like to round the value. But again, be aware of the problem mentioned above.

If you like to have an output with a limited number of decimal places, just use the corresponding format string, for example "%.1lf". The default number is 6 that's why you think it's stored like this.

But the best solution for you might be to use "%g". Note: It's always a good idea to read documentation, in this case for printf().

Upvotes: 2

Related Questions