kosmoplan
kosmoplan

Reputation: 497

Number of decimal digits in C

I like to change the number of decimal digits showed whenever I use a float number in C. Does it have something to do with the FLT_DIG value defined in float.h? If so, how could I change that from 6 to 10?

I'm getting a number like 0.000000 while the actual value is 0.0000003455.

Upvotes: 10

Views: 95593

Answers (4)

user5910213
user5910213

Reputation: 9

I experimented this problem and I found out that you cannot have great precision with float they are really bad .But if you use double it would give you the right answer. just mention %.10lf for precision upto 10 decimal points

Upvotes: 0

paulsm4
paulsm4

Reputation: 121649

@kosmoplan - thank you for a good question!

@epsalon - thank you for a good response. My first thought, too, was "float" vs. "double". I was mistaken. You hit it on the head by realizing it was actually a "printf/format" issue. Good job!

Finally, to put to rest some lingering peripheral controversy:

/*
 SAMPLE OUTPUT:
  a=0.000000, x=0.012346, y=0.012346
  a=0.0000003455, x=0.0123456791, y=0.0123456789
 */
#include <stdio.h>

int
main (int argc, char *argv[])
{
  float  x = 0.0123456789, a = 0.0000003455;
  double y = 0.0123456789;
  printf ("a=%f, x=%f, y=%lf\n", a, x, y);
  printf ("a=%.10f, x=%.10f, y=%.10lf\n", a, x, y);
  return 0;
}

Upvotes: -1

epsalon
epsalon

Reputation: 2294

There are two separate issues here: The precision of the floating point number stored, which is determined by using float vs double and then there's the precision of the number being printed as such:

float foo = 0.0123456789;
printf("%.4f\n", foo);  // This will print 0.0123 (4 digits).

double bar = 0.012345678912345;
printf("%.10lf\n", bar);  // This will print 0.0123456789

Upvotes: 18

user529758
user529758

Reputation:

You're running out of precision. Floats don't have great precision, if you want more decimal places, use the double data type.

Also, it seems that you're using printf() & co. to display the numbers - if you ever decide to use doubles instead of floats, don't forget to change the format specifiers from %f to %lf - that's for a double.

Upvotes: -1

Related Questions