Search code examples
iphonensdecimalnumber

Examples of doing decimal math in iPhone


I'm pulling decimal values from a sql table as a text field which i then convert to an NSDecimalNumber (this is simply because i didnt know read/write decimal values to sqllite).

Anyway, now i've hit a wall now that im trying to do simple math routines on these decimal variables. Such as, Sum = Balance * Interest_Rate. The idea is that im working with money calculations.

Do you know of samples/tutorials that teaches how to do these operations using either NSDecimal, NSDecimalNumber, or both?

Thanks.


Solution

  • To init:

    NSString *number = @"123.4";
    NSDecimalNumber *myDecimal = [[NSDecimalNumber alloc] initWithString: number];
    

    To do what you want to do:

    NSDecimalNumber *sum = [[NSDecimalNumber alloc] initWithDecimal:[balance decimalNumberByMultiplyingBy: interest_rate];
    

    How?

    Well you make a NSDecimalNumber and alloc and then initWithDecimal. What decimal? balance multiplied (decimalNumberByMultiplyingBy) by interest_rate.