Doing calculation with NSDecimalNumber or Float

311 views Asked by At

I have to do calculation in my application, i have formules like this one :

result = Capital * rate / (1- 1/(1+ rate)^frequence)

I have read in internet that doing calculation with floats can be lossless.

Should i use NSDecimalNumber in my situation ?

1

There are 1 answers

2
Sulthan On BEST ANSWER

All numbers, including NSDecimalNumber have only a specific accuracy. Floats and Doubles are binary representation of numbers and they can represent 23 and 52 binary digits respectively (about 7 and 16 decimal digits).

That means that some numbers cannot be represented precisely. For example, consider 1 / 3 - to be represented precisely, you would need an infinite number of digits (0.333333333333...).

In most situations 16 decimal digits is more than enough, especially when the result of a calculation doesn't have to be absolutely accurate. The precision can be also affected by the order of calculations.

NSDecimalNumber can hold up to about 30 decimal digits (it doesn't represent numbers in binary), so it can hold numbers more precisely than a Double. However, calculations with NSDecimalNumber are not done natively on CPU and are much slower. It's not something you want to do if speed is necessary. We use NSDecimalNumber mainly for calculations with currency because we need high precision there (especially we want to avoid precision loss when converting to binary and back).