Convert a double into a string

Discussion in 'Mac Programming' started by ricku425, Feb 20, 2008.

  1. ricku425
    Expand Collapse
    macrumors newbie

    Joined:
    Feb 20, 2008
    #1
    I am totally new to the whole Obj-C/XCode/IB world, and at the moment, I'm just playing around with some simple i/o stuff. I am wanting to put a double value number into a string. Here's the code I'm trying to use at the moment:

    Code:
    double value = 123.45678901;
    NSString *myString = [NSString stringWithFormat:@"You're double value is %d", value];
    [outputTextField setString:myString];
    The output, however, shows up as "You're double value is 133744594".

    Is it possible to do what I'm trying to do? I've been able to get all the other data types to work (namely int and float) as I would expect them to behave.

    Any help for this complete noob would be appreciated...
     
  2. toddburch
    Expand Collapse
    macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #2
    Instead of %d, try %lf (that's ell, eff).

    %d in C/C++ is for integers. %f is for floats. %lf is for doubles.

    Todd
     
  3. ricku425
    Expand Collapse
    thread starter macrumors newbie

    Joined:
    Feb 20, 2008
    #3
    Todd-

    Thanks you so much for your reply. That got me half way there (well, technically 82% of the way...). By replacing %d with %lf, the output printed as: "You're double value is 123.456789". However, my double value is actually 123.45678901. That's not too many decimal places for a double value, is it?
     
  4. toddburch
    Expand Collapse
    macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #4
    I believe you get 6 decimal positions by default. Try %.8lf.

    Todd
     
  5. ricku425
    Expand Collapse
    thread starter macrumors newbie

    Joined:
    Feb 20, 2008
    #5
    Awesome! I looked in FOUR Obj-C programming books and couldn't find that anywhere! Thanks for the super-quick help!!
     
  6. kainjow
    Expand Collapse
    Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #6
    The Apple documentation is usually the best place to look for small things like this: String Format Specifiers
     
  7. toddburch
    Expand Collapse
    macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #7
    That is amazing, because I can't even spell Ojbective-C. Yet.
     

Share This Page