Data Formatting Guide

Number Formatters

NSNumberFormatter provides two convenient methods—stringFromNumber: and numberFromString:—that you can use to create a string representation of a number and to create a number object from a string respectively. To create a localized string representation of a number without creating a formatter object, you can use the class method localizedStringFromNumber:numberStyle:.

If you have more sophisticated requirements when parsing a string, in addition to the methods inherited from NSFormatter (such as getObjectValue:forString:errorDescription:), the getObjectValue:forString:range:error: method allows you to specify a subrange of the string to be parsed, and it returns the range of the string that was actually parsed. (In the case of failure, it indicates where the failure occurred.) It also returns an NSError object that can contain rich information about the problem.

There are many attributes you can get and set on a number formatter. When you present information to the user, you should typically simply use the NSNumberFormatter style constants to specify pre-defined sets of attributes that determine how a formatted number is displayed. If you need to generate a representation of a number in a precise format, however, you should use a format string.

Nomenclature

NSNumberFormatter provides several methods (such as setMaximumFractionDigits:) that allow you to manage the number of fraction digits allowed as input by an instance. “Fraction digits” are the numbers after the decimal separator (in English locales, the decimal separator is typically referred to as the “decimal point”).