Thread: What is the correct way to print a float?

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    147

    What is the correct way to print a float?

    I have a program that printf a float that is returned by a function like this:

    Code:
    printf("%3.1f\n", myfloat());
    ...
    float myfloat(void) {
        code....
    }
    In w32 my program has been running ok, but when run in a w64, it crash at the printf. If I change the definition of the function to return double it runs ok.

    For my surprise, in printf format string - Wikipedia, the free encyclopedia , in the "type" section I see there is no definition to print a float, but %f is for double in fixed point.

    So the question is what is the correct way to printf a float? must I cast? or is it better to return double? if so, does it have a performance penalty?

    After seeing the wikipedia I am a bit confused about it.....

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Try calling printf like this

    Code:
    printf("%3.1f\n", (double)myfloat());
    Conversion only happens only when printing. Even if you use exclusively double throughout your program rather than float, this is often not a performance difference. However, the only valid way to know is to profile your code execution using float vs double. But such minor details are normally not speed critical compared to the overall approach or algorithm being used.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Did you forward-declare the function? Otherwise you may have been lucky that the compiler's 'int' guess happens to have the same size as 'float' data type in a particular platform.

  4. #4
    Stoned Witch Barney McGrew's Avatar
    Join Date
    Oct 2012
    Location
    astaylea
    Posts
    420
    It shouldn't matter. If you pass in a float it will be automatically converted to a double. Chances are your implementation's broken.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Maybe it's just your example, but your myfloat() function doesn't show an actual return value.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 07-15-2011, 03:22 PM
  2. sprintf don't print %f (float)
    By sergioms in forum C Programming
    Replies: 6
    Last Post: 07-06-2011, 11:00 AM
  3. What is the correct way to enter a float pointer?
    By Zalbik in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2003, 06:08 PM
  4. What is wrong here, just won't print the correct numbers
    By Unregistered in forum C++ Programming
    Replies: 16
    Last Post: 05-10-2002, 03:31 PM
  5. why does'nt this print the average as a float..
    By morone in forum C Programming
    Replies: 0
    Last Post: 08-30-2001, 12:24 PM

Tags for this Thread