views:

787

answers:

2

Hi

Im working on an iPhone application and want to represent money ($) amounts. I can't use float because they introduce certain amount of rounding errors. What can I use?

Im thinking of defining my own Money class and store dollars and pennies as NSInteger internally.

@interface Money : NSObject {
    //$10.25 is stored as dollas=10 and pennies=25
    NSInteger dollars;
    NSInteger pennies;
}

Another possible representation (easier for adding and multiplying) would be to use a single NSInteger as pennies.

@interface Money : NSObject {
    //$10.25 is stored as pennies=1025
    NSInteger pennies;
}

What are your thoughts? is there a "BigDecimal" type I can use? Thanks Gonso

+3  A: 

NSDecimalNumber

Doug Currie
+10  A: 

Use NSDecimalNumber. Sure it has overhead, but unless you can prove that's a problem, you'll love the accuracy it gives you.

http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/ http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/Reference/Reference.html

J. John