Thread: float/double variable storage and precision

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    38

    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
    chris

  2. #2
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    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.
    Away.

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    38

    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)?
    chris

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    38

    done

    found it....for a double I need to use "%lg"
    chris

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Or %lf

Popular pages Recent additions subscribe to a feed