Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format int to NSString with displaying the + sign for positive numbers in iOS

AFAIK its impossible using just [NSString stringWithFormat:@"%d"] since there is no specifiers for explicit displaying the + displaying, at least i didn't find it at Apple Developer String Format Specifiers
So it looks like I have to use NSNumberFormatter in my case. I found how to set the plus sign representation but can't figure out how to achieve my goal. I tried

    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setPositiveFormat:@"+0"];
    NSString strNumber = [numberFormatter stringFromNumber:[NSNumber numberWithInt:intSomeNumber]];

but I'm afraid it would cut numbers GT 9 to 1 digit and I don't want that. I just want to display any positive int with + and any negative with -. Is this the right way maybe:

NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setPositiveFormat:@"+#"];
NSString strNumber = [numberFormatter stringFromNumber:[NSNumber numberWithInt:intSomeNumber]];
like image 444
Stan Avatar asked Nov 29 '12 11:11

Stan


2 Answers

From the very page you linked:

For more details, see the IEEE printf specification.

Now from the IEEE printf specification:

+ The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.

Example:

NSLog(@"%+f", 3.455677);

Result:

+3.455677
like image 148
Kreiri Avatar answered Oct 21 '22 11:10

Kreiri


[numberFormatter setPositivePrefix:@"+"];
like image 31
omz Avatar answered Oct 21 '22 11:10

omz