Don't localize numbers this way


I just finished chapter 17 of the wonderful book, but this chapter feels weak, thin, and out of place. While the goal is certainly not to provide a complete overview of localization, it does provide one blaring example of what not to do when localizing numbers. In particular, the code that recommends showing the currency as :

NSString *currencySymbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
[[cell valueLabel] setText:[NSString stringWithFormat:@"%@%d", currencySymbol, [p valueInDollars]]];

will run and might appear correct, but is not. Not all regions display currencies in the same way. For example, while one might write $100 in the US, we write 100 (euro) in France. (Note: I had to write (euro) instead of the symbol in this message because of a text encoding bug.) Furthermore, some euro-zone regions write that as (euro) 100 (note the space). While completely understandable, writing (euro)100 just looks wrong. Fortunately, the NSNumberFormatter (which is just like the NSDateFormatter but for numbers) handles all these subtleties for us. So the above code should have been written as:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumFractionDigits:0];
[[cell valueLabel] setText:[formatter stringFromNumber:[NSNumber numberWithInt:[p valueInDollars]]];


Thank you for this tip - one of the most lucid descriptions I have ever read!
10 out of 10.


Great tip, eaganj! But don’t be too hard on the authors. I think that 99% of the readers of the book are saying “Gimme code techniques!” and aren’t interested in internationalization issues.

Hats off to Apple for building a pretty decent set of mechanisms to allow us to do this. Those of us outside of the USA are probably slightly more aware of the need to. I’m Australian, and I hate the US’s being stuck on a non-metric measurement system, and hate their use of US-letter paper rather than A4.

And to those Americans here… yes, I’ve lived in the USA, and yes, your paper size can grow on you if that’s all that you have, but the rest of the world uses A4! :slight_smile:


You are correct, I simply couldn’t find another place to use NSLocale without having the reader put in a bunch of extra work. If you find a place, let me know.