NSString stringwithformat: Padding 2 strings with unknown length

末鹿安然 提交于 2019-12-05 11:43:54

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)

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!