Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString stringwithformat: Padding 2 strings with unknown length

I'm having a problem doing something with NSString stringWithFormat...

The problem is as follows:

First of all, I have 2 strings. Which are money quantities.

The thing, is that i want to create 1 string with these two.

For ex:

strF = [NSString stringWithFormat:@"First: %@   Second: %@", value1, value2];

I want to know if there is possible to make a correct padding between First and Second.. Assuming the first string is not the same length always..

I want to make this:

First: 10,000.00         Second: 788.00
First: 10.00             Second: 788.00
First: 0.00              Second: 788.00
First: 100.00            Second: 788.00
First: 5.00              Second: 788.00
like image 744
Tidane Avatar asked Jun 06 '13 16:06

Tidane


2 Answers

revision Here's a better way, using NSNumberFormatter:

First create and configure your formatter like this:

NSNumberFormatter * formatter = [[ NSNumberFormatter alloc ] init ] ;
[ formatter setFormatWidth:20 ] ;
[ formatter setPaddingCharacter:@" " ] ;
[ formatter setFormatterBehavior:NSNumberFormatterBehavior10_4 ] ;
[ formatter setNumberStyle:NSNumberFormatterDecimalStyle ] ;
[ formatter setMinimumFractionDigits:2 ] ;
[ formatter setMaximumFractionDigits:2 ] ;

Once you have created your formatter, your code becomes:

strF = [ NSString stringWithFormat:@"First: %@ Second: %@", [ formatter stringFromNumber:value1 ], [ formatter stringFromNumber:value2 ] ] ;

You'll get the (thousands) separators (in the current locale) etc.

I would create the formatter in a class method (something like +numberFormatter or in a dispatch_once block) You could even add it to NSNumberFormatter via a category and have something like +[ NSNumberFormatter mySharedFormatter ]


You can use the field width specifier. It does this:

NSString * value1String = ... from NSNumberFormatter to get commas inserted ;
[ NSString stringWithFormat:@"First: %20s Second: %0.2f", [ value1String UTF8String ], value2 ]

Where "20" is the width of the column. (Replace by desired width). There's other options, like right justify, etc. Do man printf for more.

If you want to add the commas, NSNumberFormatter should be able to do that.

(Actually, you probably want your decimals to line up too, right? You could try % 20.2f)

like image 123
nielsbot Avatar answered Sep 18 '22 17:09

nielsbot


Well, you need to set a maximum length of value1 at least, and then you can do something like

int maxLength = MAX(15, value1.length); // Prevent cropping anyway
NSString* formattedValue1 = [value1 stringByPaddingToLength:maxLength withString:@" " startingAtIndex:0]
strF = [NSString stringWithFormat:@"First: %@ Second: %@", formattedValue1, value2];
like image 33
tia Avatar answered Sep 19 '22 17:09

tia