Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a NSNumber as percentage (%) with one decimal place using NSNumberFormatter

I am trying to format a NSNumber containing a value of 0.305 as "30.5%".

However, my following code does not work:

[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];

How can I specify that the number should be formatted as percentage with one decimal place?

like image 407
AlexR Avatar asked Feb 24 '12 15:02

AlexR


3 Answers

This works for me:

[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setMinimumFractionDigits:1];
like image 125
Sebastien Windal Avatar answered Nov 12 '22 00:11

Sebastien Windal


Edited for the actual correct answer:

[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setMinimumFractionDigits:1];
like image 40
Bob de Graaf Avatar answered Nov 12 '22 02:11

Bob de Graaf


Try

float percent = 0.305;

NSString *formattedPercentText = [NSString stringWithFormat:@"%.1f%%", percent * 100];
like image 4
Nick Weaver Avatar answered Nov 12 '22 00:11

Nick Weaver