Converting float to NSString

Discussion in 'iPhone/iPad Programming' started by liptonlover, Jan 14, 2009.

  1. macrumors 6502a

    #1
    Here's the code...

    Code:
    - (void)sendVariable:(float)variable toOutlet:(id)outlet {
    	[outlet setText:variable];
    }
    Here's the error.
    error: incompatible type for argument 1 of 'setText:'

    The text property in UILabel accepts NSStrings only but I need it to display float values. I looked under NSString but couldn't find anything such as 'stringFromDouble' so I don't know what to do.

    Also... I got this warning.
    Code:
    warning: conflicting types for '-(void)sendVariable:(float)variable toOutlet:(id)outlet'
    I don't understand what this warning means. Can anyone help?
    Thanks in advance, Nate
     
  2. Moderator

    dejo

    Staff Member

    #2
    Look into using stringWithFormat.
     
  3. macrumors 603

    jeremy.king

    #3
    ^
    |
    |
    what he said
     
  4. macrumors 6502a

    #4
    Ok, here's the code now.
    Code:
    - (void)sendVariable:(float)variable toOutlet:(id)outlet {
    	[string initWithFormat:@"%f"];
    	[string setValue:variable];
    	[outlet setText:string];
    	[string release];
    }
    I have one more problem. Now that I've formatted the NSString instance, I don't know how to give it a value. It doesn't have a setValue: property or method, nor does it have a setText: one. Sorry if I'm missing something painfully obvious, it wouldn't be the first time.
     
  5. macrumors 6502a

    #5
    http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

    Code:
    - (void)sendVariable:(float)variable toOutlet:(id)outlet {
    	[outlet setText:[NSString stringWithFormat:@"%f", variable]];
    }
     
  6. macrumors 6502a

    #6
    Thanks, I didn't know stringWithFormat could then accept a variable as a second argument.
    Thanks, Nate
     
  7. macrumors 6502a

    #7
    NSString behaves in roughly the same way as C's printf (http://en.wikipedia.org/wiki/Printf#1970s:_C.2C_Lisp) so will take as many arguments as you care to add.
     
  8. macrumors 6502a

    #8
    Thanks :)
    Cheers, Nate
     

Share This Page