0

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?

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Well what if I want it to be -2? The + is supposed to force a + or - in front of the number, and this solution gets me "+-02"....
@radiopaque Edited my answer. It's not the cleanest code, but it works.
@radiopaque I've done some debugging and finally found the best answer. Hope it's what you've been looking for.
Yes! It's a bit counter-intuitive (to me), but the sign counts as a character. So for two actual digits, plus a sign, you'd need THREE characters as in your answer. Thank you very much!
0

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

1 Comment

I couldn't get this work. It does add the sign properly, but doesn't add the leading zeros. I'm curious if there is a solution for this.
0

Yes Adam is right:

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

1 Comment

Yes it's 3 decimal places and not 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.