I need to print out a float value with 16 significant digits.
Right now when I print, it prints out
i.e 2.555556
when I want it to print out: 2.555555555555556 /// A total of 16 digits
My printf specifier currently is : "%20.18lf"
ideas?
I need to print out a float value with 16 significant digits.
Right now when I print, it prints out
i.e 2.555556
when I want it to print out: 2.555555555555556 /// A total of 16 digits
My printf specifier currently is : "%20.18lf"
ideas?
If the value is of type float
, you're probably not going to get more than about 7 significant digits after the decimal point. If it's of type double
, you can get about 15. Depending on the system, long double
may be no more precise than double
; on mine, I get about 17 significant digits after the decimal point.
Most floating-point code uses type double
; float
is much less precise and often not significantly faster.
I'm a little surprised that you got 2.555556
rather than something like 2.555555582046508789
with a "%20.18lf"
format.
Incidentally, the l
(lowercase L) is not necessary. The format for double
is "%f"
, and float
arguments to printf
are promoted to double
, so "%f"
is correct for both float
and double
. The format for long double
is "%Lf"
.
Here's a test program I wrote:
#include <stdio.h>
int main(void) {
const float f = 23.0/9.0;
const double d = 23.0/9.0;
const long double ld = 23.0L/9.0L;
printf("%20.18f\n%20.18f\n%20.18Lf\n", f, d, ld);
return 0;
}
and the output I got on my system:
2.555555582046508789
2.555555555555555358
2.555555555555555556
The following code works well (you have to enable C99 as %lf
specifier is not part of earlier standards):
#include <stdio.h>
int main(void)
{
volatile float v = 2.555555555555556;
printf("%20.18lf\n", v);
return 0;
}
Prints the following:
$ gcc -std=c99 -Wall -pedantic -o test ./test.c
$ ./test
2.555555582046508789
$
If value is shorter, say 2.5, it right-pads it with zeros - 2.500000000000000000
.
So you have an error elsewhere. Generally, you have to post a minimal self-consistent code example that reproduces the problem. Otherwise you are on your own.
C float or double is not precise enough, basically you need a high precision division function. Here is what I wrote. It is for integer division. You may need to revise it for float division.
int dividend=121, divisor=9;
int quotient,remainder;
//first print out the number before decimal point
quotient=dividend/divisor;
printf("%d", quotient);
remainder=dividend-quotient*divisor;
//print out decimal point
printf(".");
int digit_num=20;//this can be any precision you want
//second we calculate the number after decimal point
for(int i=0;i<digit_num;i++)
{
remainder=remainder*10;
quotient=remainder/divisor;
remainder=remainder-quotient*divisor;
printf("%d", quotient );
dividend=remainder;
}
printf("\n");
printf("%d digits after decimal point has been printed out\n", digit_num );