Using Decimal Numbers

NSDecimalNumber is an immutable subclass of NSNumber that provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10 exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer between -128 and 127.

In the course of doing arithmetic, a method may produce calculation errors, such as division by zero. It may also meet circumstances where it has a choice of ways to round a number off. The way the method acts on such occasions is called its “behavior.”

Behavior is set by methods in the NSDecimalNumberBehaviors protocol. Every NSDecimalNumber argument called behavior requires an object that conforms to this protocol. For more on behaviors, see the specifications for the NSDecimalNumberBehaviors protocol and the NSDecimalNumberHandler class. Also see the defaultBehavior method description.

C Interface to Decimal Numbers

You can access the arithmetic and rounding methods of NSDecimalNumber through group of C functions:

You might consider the C interface if you don’t need to treat decimal numbers as objects—that is, if you don’t need to store them in an object-oriented collection like an instance of NSArray or NSDictionary. You might also consider the C interface if you need maximum efficiency. The C interface is faster and uses less memory than the NSDecimalNumber class.

If you need mutability, you can combine the two interfaces. Use functions from the C interface and convert their results to instances of NSDecimalNumber.