4

I am trying to build a small table using NSString. I cannot seem to format the strings properly.

Here is what I have

[NSString stringWithFormat:@"%8@: %.6f",e,v]

where e is an NSString from somewhere else, and v is a float.

What I want is output something like this:

Grapes:       20.3
Pomegranates:  2.5
Oranges:      15.1

What I get is

Grapes:20.3
Pomegranates:2.5
Oranges:15.1

How can I fix my format to do something like this?

4 Answers 4

6

you could try using - stringByPaddingToLength:withString:startingAtIndex:

Sign up to request clarification or add additional context in comments.

Comments

3
NSDictionary* fruits = [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithFloat:20.3], @"Grapes",
                        [NSNumber numberWithFloat:2.5], @"Pomegranates",
                        [NSNumber numberWithFloat:15.1], @"Oranges",
                        nil];
NSUInteger longestNameLength = 0;
for (NSString* key in [fruits allKeys])
{
    NSUInteger keyLength = [key length];
    if (keyLength > longestNameLength)
    {
        longestNameLength = keyLength;
    }
}
for (NSString* key in [fruits allKeys])
{
    NSUInteger keyLength = [key length];
    NSNumber* object = [fruits objectForKey:key];
    NSUInteger padding = longestNameLength - keyLength + 1;
    NSLog(@"%@", [NSString stringWithFormat:@"%@:%*s%5.2f", key, padding, " ", [object floatValue]]);
}

Output:

Oranges:      15.10
Pomegranates:  2.50
Grapes:       20.30

Comments

1

The NSNumberFormatter class is the way to go!

Example:

NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setPaddingCharacter:@"0"];
[numFormatter setFormatWidth:2];
NSString *paddedString = [numFormatter stringFromNumber:[NSNumber numberWithInteger:integer]];
[numFormatter release];

Comments

0

I think you want something like

[NSString stringWithFormat:@"%-9@ %6.1f",[e stringByAppendingString:@":"],v]

since you want padding in front of the float to make it fit the column, though if the NSString is longer than 8, it will break the columns.

%-8f left-aligns the string in a 9-character-wide column (9-wide since the : is appended to the string beforehand, which is done so the : is at the end of the string, not after padding spaces); %6.1f right-aligns the float in a 6-char field with 1 decimal place.

edit: also, if you're viewing the output as if it were HTML (through some sort of web view, for instance), that may be reducing any instances of more than one space to a single space.

Comments

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.