Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Chapter 5. Numbers > Performing Decimal Arithmetic - Pg. 105

Performing Decimal Arithmetic 105 Performing Decimal Arithmetic 6 7 8 9 10 11 12 13 14 15 16 17 18 NSDecimalNumber *one = [NSDecimalNumber one]; NSDecimalNumber *fortyTwo = [NSDecimalNumber decimalNumberWithString: @"42" ]; NSDecimalNumber *sum = [one decimalNumberByAdding: fortyTwo]; NSDecimal accumulator = [sum decimalValue]; NSDecimal temp = [fortyTwo decimalValue]; NSDecimalMultiply(&accumulator, &accumulator, & temp, NSRoundPlain); temp = [one decimalValue]; NSDecimalAdd(&accumulator, &accumulator, &temp, NSRoundPlain); NSDecimalNumber *result = [NSDecimalNumber decimalNumberWithDecimal: accumulator]; From: decimal.m C gives you two options for working with numbers: integers and floating-point values. Floating-point values are made of two components: a mantissa and an exponent. Their value is two to the power of the exponent, multiplied by the mantissa. The problem with floating-point values is that they are binary. This means that their precision is defined in terms of binary digits, which is not always what you want. For a financial application, for example, you may need to store amounts to exactly four decimal places. This is not possible with floating-point values; a value such as 0.1 cannot be represented by any finite