# Precision Math in Cocoa: NSDecimalNumber

Arithmetic underflow and the 2′s compliment representation of numbers is serious problems in writing algorithms, especially when dealing with financial transactions. A lot of developers skirt around this problem by using double precision, but that is asking for trouble in applications–such as financial applications–that are more sensitive to these problems.

To get around this, different languages and libraries have implemented objects allow for either fixed or arbitrary precision. Java has BigDecimal, python has decimal, and various languages can take advantage of bc.

Objective-C–via the Cocoa library–has NSDecimalNumber. It isn’t quite an arbitrary precision library, but is suitable for a wide range of applications that need precise mathematical calculations.

NSDecimalNumber is fixed precision rather than arbitrary precision. It works by representing decimals as $mantissa \times 10^{exponent}$, where the $mantissa$ is limited to 38 characters (base-10) while the $exponent$ needs to be between -128 and 127. Any number within those parameters will be represented exactly, and it allows for rounding behavior (e.g., bankers rounding with NSRoundBankers).

The library works in a very similar manner to the Java and python libraries, so I won’t go into the details of how to use it here.

Basically though it allows you to add, subtract, multiply, divide, and raise to a power. This can use either the default behavior or that behavior can be configured by a NSDecimalNumberBehaviors. As a convenience, Cocoa provides a default handler along with an easy way to create them in them NSDecimalNumberHandler class.

Just as in Java BigDecimal inherits from java.lang.Number and in python
Decimal behaves like a number, NSDecimalNumber inherits from NSNumber.