Formatting numbers is easy

When you have some numbers that you need to show in your user interface, you shouldn’t just stick them in a string using whatever old library function you happen to have. Especially printf in C, toString in Java, and others like these are only suitable for debugging, because they have no idea about how to format numbers properly according to the user’s regional settings. The ways to write numbers have differences across languages and countries, especially with the characters used to separate the whole part and the decimal part, and also with regard to how large numbers are grouped to make them easier to read. Luckily you don’t have to figure out the details yourself.

Instead of traditional programmer-style functions, use the convenient API methods provided by your platform. They do all the heavy lifting and work out the details for you. For example, in iOS you use NSNumberFormatter class from the Foundation framework. Since iOS 4.0 it has offered a very nice way to get a locale-specific representation of a number so that it honors the current user settings. NSNumberFormatter has a class method called localizedStringFromNumber:numberStyle:, so you can use it without even creating an instance of the class.

So, if you have previously said:

self.scoreLabel.text = [[NSNumber numberWithInt:score] stringValue];

you only need to make the leap to:

self.scoreLabel.text = 
        localizedStringFromNumber:[NSNumber numberWithInt:score]

and you’re done. (With the new Objective-C literal syntax you could even say just @(score) instead of [NSNumber numberWithInt:score].)

If you have some additional text surrounding the number, use a localized template loaded from the bundle with NSLocalizedString(key, comment), as usual. However, because localizedStringFromNumber:numberStyle: returns an NSString, make sure that your template uses an object placeholder %@, instead of a primitive type like %i.

If you need help with any of this, maybe you could use our internationalization training?

And if you want to know how to do this also in Android and Windows Phone, contact us to find out how we can help you!

Updated 2012-10-30:

  • The name of the Foundation class is NSNumberFormatter, of course.
  • Added remark about new Objective-C literal syntax.