Question

I have simple calculating in my app

-(IBAction)calculate {
    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setRoundingMode: NSNumberFormatterRoundHalfUp];
    [nf setMaximumFractionDigits: 2];

    float value1 = [[nf numberFromString: textField1.text] floatValue];
    float value2 = [[nf numberFromString: textField2.text] floatValue];

    float x = value1 * value2 / 100;
    label2.text = [nf stringFromNumber: [NSNumber numberWithFloat: x]];

    [nf release];
}

Now, when I calculate result looks like this: ,75 or 64,5

I need to my result looks like this: 0,75 or 64,50

My problem is there no zero before the decimal point or after second decimal

Was it helpful?

Solution

Where you set your text in the UILabel, use

label2.text = [NSString stringWithFormat:@"%.2f",x];

This will ensure you get 2 decimal places. You don't even need a number formatter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top