NSString stringWithFormat question

I am trying to create a small table using NSString. I cannot format strings correctly.

That's what i

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

where e is an NSString from another place and v is a float.

What I need is to output something like this:

 Grapes: 20.3 Pomegranates: 2.5 Oranges: 15.1 

I get

 Grapes:20.3 Pomegranates:2.5 Oranges:15.1 

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

+4
source share
4 answers
 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]]); } 

Conclusion:

  Oranges: 15.10
 Pomegranates: 2.50
 Grapes: 20.30
+3
source

you can try using - stringByPaddingToLength: withString: startAtIndex:

+6
source

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]; 
+1
source

I think you want something like

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

since you want to fill before the float so that it matches the column, although if NSString is longer than 8, it breaks the columns.

%-8f left-aligns a line in a column with a width of 9 characters (9 times, since : added to the line in advance, which is done so that : is at the end of the line, and not after filling in the spaces); %6.1f aligns the correction flag in the 6-char field with 1 decimal point.

edit: also, if you are viewing the output as if it were HTML (for example, through some kind of webview), this could reduce any instance of more than one space to one place.

0
source

Source: https://habr.com/ru/post/896278/


All Articles