Filippos Filippoglou
Filippos Filippoglou

Reputation: 51

Format number as percent

I have written this code and I want to format the number z as percent.

float l = ([textField2.text floatValue]);
float g = ([textField1.text floatValue]);

float x = l/1.23;
float y = x-g;
float z = y/l;

label.text = [[NSString alloc] initWithFormat:@"%2.2f \%",z]; 

Upvotes: 3

Views: 3188

Answers (3)

Chakalaka
Chakalaka

Reputation: 2827

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];

[numberFormatter setMinimumFractionDigits:2];  //optional
....

NSNumber *number = [NSNumber numberWithFloat:0.435];

NSLog(@"%@", [numberFormatter stringFromNumber:number] );

43,50 %

Upvotes: 4

Ilanchezhian
Ilanchezhian

Reputation: 17478

Make your code as follows.

label.text = [[NSString alloc] initWithFormat:@"%2.2f %%",(z*100)]; 

Upvotes: 6

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

You need to use %% in order to print a percent sign in a format string.

Upvotes: 3

Related Questions