Thread: float setting decimal places

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    26

    float setting decimal places

    I am trying to find out when using float in a calculation how to set the number of decimal places. For example my code below
    Code:
                                                                                                                                                                                    #include stdio.h>
    int main()
    {
     float x=123.0;
     float y=69.0;
     float answer=y*x;
    printf("the answer is %f\n",answer);
    return(0);
    }
    This returns an answer 8487.0000 I would like it not to show all the decimal places. However if the sum has decimal places I would like to select the number of decimal places shown Thanks Rodney

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    read all about it here printf - C++ Reference

    C and C++ are the same for this topic

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Note, I don't think there is anything built in to printf that does exactly what you want, but you can use the * in the precision field, and give it either a 0 (no decimal places) or a positive value (e.g. 4) for how many decimal places you want displayed. The modff function will help you determine if there was a fractional part.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-05-2011, 11:32 PM
  2. Round float to 2 decimal places
    By tesla in forum C Programming
    Replies: 8
    Last Post: 09-15-2009, 12:51 AM
  3. Float Decimal Places
    By TyrioN in forum C Programming
    Replies: 1
    Last Post: 08-15-2004, 02:30 AM
  4. Replies: 10
    Last Post: 06-12-2002, 03:15 PM
  5. setting a float to 4 digit decimal precision
    By river-wind in forum C Programming
    Replies: 8
    Last Post: 01-21-2002, 05:03 PM