#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    17
    Rep Power
    0

    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

    #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
  3. Lord of Dorkness
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2004
    Location
    Central New York. Texan via Arizona, out of his element!
    Posts
    8,524
    Rep Power
    3269
    You can't do that with printf directives. You can sprintf to a string and manipulate in various ways.
    Functionality rules and clarity matters; if you can work a little elegance in there, you're stylin'.
    If you can't spell "u", "ur", and "ne1", why would I hire you? 300 baud modem? Forget I mentioned it.
    DaWei on Pointers Politically Incorrect.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    17
    Rep Power
    0
    Originally Posted by DaWei_M
    You can't do that with printf directives. You can sprintf to a string and manipulate in various ways.
    I actually managed to get some help and read something on a tutorial and got it to work.

    #include <stdio.h>
    int main()
    {
    float x=123.45;
    float y=69.01;
    float answer=y*x;

    printf("the answer is %4.2f\n",answer);

    return(0);
    }

    now the plot thickens as I need to do it to several numbers.

    Comments on this post

    • dwise1_aol disagrees : That is not what you were asking for.

IMN logo majestic logo threadwatch logo seochat tools logo