Floats

This is a discussion on Floats within the C Programming forums, part of the General Programming Boards category; I have a value assigned to a variable called x (float) of 12.56. I have another int variable called y. ...

  1. #1
    JFK
    JFK is offline
    Registered User
    Join Date
    Oct 2001
    Posts
    15

    Question Floats

    I have a value assigned to a variable called x (float) of 12.56.
    I have another int variable called y. If I want to output 12 (from the 12.56) i can do:

    y = x;
    printf("%d", y); /*truncates the 12.56 and out puts 12 only*/

    Any ideas how I just output the .56 of the 12.56??

  2. #2
    Registered User Strider's Avatar
    Join Date
    Aug 2001
    Posts
    149
    Here is a sample of what you could do:
    Code:
    #include <stdio.h> 
    
    int main() 
    { 
        float x = 12.56f;
        int y;
    
        y = (int)x;
        printf("%d plus %.2f equals %.2f\n", y, (x - y), x);
        /* %.2f will display float values with decimal precision of 2. */
    
        return 0;
    }
    David
    One Ring to rule them all, One Ring to find them,
    One Ring to bring them all and in the darkness bind them
    In the Land of Mordor where the Shadows lie.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145

    float Var=12.56;
    printf("%f", Var-(float)((int)Var) );

    I just made that up, not sure if it works however. This is what it does:

    (int)Var //12.56 --> 12

    (float)(...) //(int)12 --> (float)12

    Var - (...) //12.56 - 12 --> 0.56
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. variables larger than floats
    By a.mlw.walker in forum C Programming
    Replies: 13
    Last Post: 04-23-2009, 02:28 AM
  2. Reading errors in floats
    By Improvolone in forum C++ Programming
    Replies: 8
    Last Post: 03-21-2006, 02:20 PM
  3. % and floats
    By confuted in forum C++ Programming
    Replies: 2
    Last Post: 08-04-2003, 09:41 PM
  4. comparing two arrays of floats
    By COBOL2C++ in forum C++ Programming
    Replies: 7
    Last Post: 07-16-2003, 03:22 AM
  5. Using floats in conditional statements
    By DBB in forum C++ Programming
    Replies: 3
    Last Post: 09-12-2001, 07:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21