John Smith
John Smith

Reputation: 12797

NSString stringWithFormat question

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?

Upvotes: 4

Views: 5392

Answers (4)

Jack
Jack

Reputation: 2671

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];

Upvotes: 1

Jonathan Lund
Jonathan Lund

Reputation: 61

you could try using - stringByPaddingToLength:withString:startingAtIndex:

Upvotes: 6

Isaac
Isaac

Reputation: 10834

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.

Upvotes: 0

Shaggy Frog
Shaggy Frog

Reputation: 27601

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

Upvotes: 3

Related Questions