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:

NSDecimalAddAdds two decimal values.
NSDecimalCompactCompacts the decimal structure for efficiency.
NSDecimalCompareCompares two decimal values.
NSDecimalCopyCopies the value of a decimal number.
NSDecimalDivideDivides one decimal value by another.
NSDecimalIsNotANumberReturns a Boolean that indicates whether a given decimal contains a valid number.
NSDecimalMultiplyMultiplies two decimal numbers together.
NSDecimalMultiplyByPowerOf10Multiplies a decimal by the specified power of 10.
NSDecimalNormalizeNormalizes the internal format of two decimal numbers to simplify later operations.
NSDecimalPowerRaises the decimal value to the specified power.
NSDecimalRoundRounds off the decimal value.
NSDecimalStringReturns a string representation of the decimal value.
NSDecimalSubtractSubtracts one decimal value from another.

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.