Question

#include <stdio.h>
#include <wchar.h> 
int main()
{
    double f = 1717.1800000000001;
    wprintf(L"double      %.20G\n", f);
    return 0;
}

outputs (and expected below):

double      1717.1800000000000637
double      1717.1800000000001

This is on Ubuntu 11.10 x64 (but also when compiling for 32 bit).

The problem that I try to solve, is that on Windows it outputs the number exactly like in code, and I need to make low-level formatting (swprintf) to work like in Windows, for portability issues.

Was it helpful?

Solution

1717.1800000000001 is not exactly representable as double, so you only get a value near to it in f. The value stored in f is exactly 1717.180000000000063664629124104976654052734375.

The problem is now that windows does only output 17 significant digits, although 20 were requested (which is a known bug, AFAIK it's somewhere in their bug database).

If you can't limit the field length to a sane value (like "%.17G"), you need a wrapper to mimic this bug.

OTHER TIPS

wprintf function is implemented by standard C library, not by gcc.

Number 1717.1800000000001 has 13 digits after the floating point. However, it doesn't have exact representation in 64-bit binary floating point format.

Format "%.20G" requires outputting 20 significant digits which is the count of digits in 1717.1800000000000637. Hence this output is what expected. Either Windows standard C library treats the format differently or makes incorrect rounding.

On the other hand, you can require a specific number of digits after the floating point by using "%f" format, e.g. "%.13f" rounds the output to exactly 13 digits after the floating point an it prints 1717.1800000000001 as expected.

Well, your expected output conflicts with your format string. "%.20G" means you want 20 significant digits, and that's what you're getting. If you want 17 significant digits, as your expected output has, use "%.17G".

double f = 1717.1800000000001;

This line of code cannot be executed accurately. The constant has 17 decimal digits of precision, a double has 15.9.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top