coder
coder

Reputation: 53

Floating point results

In my C code:

I see some of the results in floating point come out to be for example 2.404567E+1. it seems to me that for results less then 1 the results turn out to be in some exponential series.

So, I have 2 questions:

  1. how can I get the result rounded off to some digits ie instead of 5.23542342734 I just want the result to be 5.23

  2. How can I get rid of exponential results and get results as for example 0.1648 instead of 1.6483517E-1

Upvotes: 2

Views: 104

Answers (2)

phoxis
phoxis

Reputation: 61960

Adjust format string:

 printf ("%.2f", float_data);

http://linux.die.net/man/3/printf

Or to use to truncate/approximate the value to some decimal places, i think the following should work:

trunc = floor (float_val * 10000) / 10000;

The above will preserve only upto 4 decimal places of float_var and store it to trunc. Use round () if needed.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

You can control the output format of printf() (I'm assuming you're talking about printf()?) in a number of ways. e.g.:

printf("%.2f\n", 5.23542342734);  // Prints "5.23"
printf("%.4f\n", 1.6483517E-1);   // Prints "0.1648"

See e.g. http://www.cplusplus.com/reference/clibrary/cstdio/printf/ (or a million other references out there on the internet) for more details on format specifiers for printf().

Upvotes: 8

Related Questions