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
)