Casting an int to a string and outputting the value to a label

Discussion in 'iPhone/iPad Programming' started by philwa2, Jul 30, 2008.

  1. macrumors newbie

    Joined:
    Jul 12, 2008
    #1
    Hello,

    Im trying to cast an int into a string so that I can output the value to the text property of a label - the code below generates a random number and assigns the value to the variable "generated" I then want to take this value convert it to a string and assign it the text of the label.

    Does anyone know how to do this?

    - (IBAction)clearText {
    int generated;
    generated = (random() % 100) + 1;
    mainText.text = generated;
    }
     
  2. macrumors member

    Joined:
    Jul 9, 2008
    #2
    NSString

    Use

    label.text = [NSString stringWithFormat:mad:"%d", generated];

    stringWithFormat works like printf in c. You can pass various formats to control the output and you can have multiple replacement values in the format string. For example,

    [NSString stringWithFormat:mad:"You have clicked %d out of %d buttons or %1.2f%%", var1, var2, (double)var1/(double)var2];

    might yield, "You have clicked 4 out of 5 buttons or 80.00%"
     
  3. macrumors 68000

    Joined:
    Nov 3, 2007
    #3
    to put it in the label use the following code
    Code:
    labelName.text = [[NSNumber numberWithInt:variable] stringValue];
    
     

Share This Page