Carelinkz
Carelinkz

Reputation: 936

Converting integer into formatted string

How would I format an integer when I convert it to a string? For example:

NSString *date = [NSString stringWithFormat:
       @"...somestuff... %+02d00", ...., gmtOffset];

The above does not work properly. What I want is, for example, +0200 to appear. I should think that %+02d would convert my integer 2 into "+02". But it does no happen, I get "+2". Why is this? Am I doing something wrong or is some formatting not supported?

Upvotes: 0

Views: 217

Answers (3)

self
self

Reputation: 1215

Yes Adam is right:

  NSString *date = [NSString stringWithFormat:
                  @"%+03d00",2];
NSLog(@"date %@",date);

Upvotes: 0

Adam
Adam

Reputation: 26917

EDIT: I finally got it. Works for both positive and negative numbers and adds the leading zeros. Hope it helps.

NSString *str = [NSString stringWithFormat:@"%+03d00", 2];
NSLog(@"%@", str);

Upvotes: 2

calimarkus
calimarkus

Reputation: 9977

The documentation says, that there is a + as modifier. But I don't know how to exactly place/use it.

http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html

+ 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.

Link in apple documentation:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

Upvotes: 0

Related Questions