Search code examples
iosobjective-cunicodensstringstringwithformat

NSString stringWithFormat not working with special chars like currency symbols


I have been having a lot of trouble with NSString's stringWithFormat: method as of late. I have written an object that allows you to align N lines of text (separated by new lines) either centered, right, or left. At the core of my logic is NSString's stringWithFormat. I use this function to pad my strings with spaces on the left or right of individual lines to produce the alignment I want. Here is an example:

NSString *str = @"$3.00" --> 3 dollars
[NSString stringWithFormat:@"%8s", [str cStringUsingEncoding:NSUnicodeStringEncoding]] --> returns --> "   $3.00"

As you can see the above example works great, I padded 3 spaces on the left and the resulting text is right aligned/justified. Problems begin to arise when I start to pass in foreign currency symbols, the formatting just straight up does not work. It either adds extra symbols or just returns garbage.

NSString *str = @"Kč1.00" --> 3 Czech Koruna (Czech republic's currency)
[NSString stringWithFormat:@"%8s", [str cStringUsingEncoding:NSUnicodeStringEncoding]] --> returns --> "  Kč1.00"

The above is just flat out wrong... Now I am not a string encoding expert but I do know NSString uses the international standardized unicode encoding for special characters well outside basic ASCII domain.

How can I fix my problem? What encoding should I use? I have tried so many different encoding enums I have lost count, everything from NSMACOSRomanEncoding to NSUTF32UnicodeBigEndian.. My last resort will be to just completely ditch using stringWithFormat all together, maybe it was only meant for simple UTF8Strings and basic symbols.


Solution

  • If you want to represent currency, is a lot better if you use a NSNumberFormatter with currency style (NSNumberFormatterCurrencyStyle). It reads the currentLocale and shows the currency based on it. You just need to ask its string representation and append to a string. It will be a lot easier than managing unicode formats, check a tutorial here