# float/double variable storage and precision

Printable View

• 07-28-2003
cjschw
float/double variable storage and precision
I am [basically] trying to read in a number, store it to a variable (float) and then print it out. Easy enough right. I am having problems with the precision of variable.

number read in: "99.123456"
function to read it in: scanf(buff, "...%f...", &variable);
function to print it out: printf("var = %f", variable);
what gets printed out: "var = 99.123459"

it seems to round the last variable, so I tried manuelly setting the output:
function to print it out: printf("var = %10.6f", variable);
what gets printed out: "var = 99.123459"

again...
function to print it out: printf("var = %10.7f", variable);
what gets printed out: "var = 99.1234589"

again...
function to print it out: printf("var = %10.7f", variable);
what gets printed out: "var = 99.1234588623"

* what am I doing wrong?
* how can I set the precision to be exactly what I want it to be?
* I have different data that all has varying number of digits to the left of the decimal, how can I garentuee that I always read in a store the exact number?
* is there a "format specifier" for fprinting a double? Or do I just use "%f"
* if the number I am reading in only has 8 digits..and I do a "%12.10f" where is it getting the extra numbers from/

Thanks for your time, hopefully this is a question that is easy to answer. I can post my exact code if my question is not clear enough.

also
• 07-28-2003
confuted
floats and doubles, by their nature, are not necessarily precise. I believe floats normally get 7 numbers right (consistent with your results) and doubles get 14. After that, it's likely to be junk. If you just need a few more decimal places, switch your float to a double. Otherwise, you'll have to use a specialized number class instead of the built-in types.
• 07-28-2003
cjschw
printing out a double
When I do that it only prints out "00.000000", I am still using the " printf("var = %f", variable) " and sscanf(buff,"%f...") notation...do I need to use a different specifier for a double (ie. not %f)?
• 07-28-2003
cjschw
done
found it....for a double I need to use "%lg"
• 07-28-2003
swoopy
Or %lf