Thread: how to print only relevant parts of doubles' decimal places

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    10

    how to print only relevant parts of doubles' decimal places

    I have a set of doubles. I don't want to print the extra zeroes at the end, just the relevant part. Problem is, each double has a different fractional part. Take a look at some code below:

    Code:
    double x, y, z;
    x = 1.2;
    y = 1.45;
    z = 7;
    
    printf("x is %f, y is %f, and z is %f", x, y, z);
    The output of that program will be something like:
    x is 1.200000000, y is 1.45000000000, and z is 7.000000000000

    I would like it to print "x is 1.2, y is 1.45, and z is 7"
    Anyone have any ideas?

    EDIT: Thanks, matsp, for pointing out about x. I changed that.
    Last edited by octoc; 03-27-2008 at 09:55 AM.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Actually, x is uninitialized in your example.

    But it's a non-trivial problem to solve. You could write a function to find out how large the fraction is in each case, but there's no generic way to do that.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    printf("x is %g, y is %g, and z is %g", x, y, z);
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Use %g instead of %f.

    Edit: Dang you Dave Sinkula.

  5. #5
    Registered User
    Join Date
    Mar 2008
    Posts
    10
    Quote Originally Posted by Dave_Sinkula View Post
    Code:
    printf("x is %g, y is %g, and z is %g", x, y, z);
    Yay! That works! Thanks very much.

  6. #6
    Registered User
    Join Date
    Mar 2008
    Posts
    6
    Nice information , thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Scope And Parameter Passing
    By djwicks in forum C Programming
    Replies: 6
    Last Post: 03-28-2005, 08:26 PM
  2. Float Decimal Places
    By TyrioN in forum C Programming
    Replies: 1
    Last Post: 08-15-2004, 02:30 AM
  3. What kind of programs should I start writing?
    By Macabre in forum C++ Programming
    Replies: 23
    Last Post: 04-12-2003, 08:13 PM
  4. Getting Two Decimal Places
    By LostNotFound in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2003, 08:34 PM
  5. decimal places
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 07:08 PM