14

Which objective-c type is appropriate for handling money? I need something which is Core Data compatible.

Moshe
  • 57,511
  • 78
  • 272
  • 425

1 Answers1

16

There are two solutions:

  • Use an int, and always keep track of monetary values in cents (or the smallest possible division of whatever currency you're using). Use only integer calculations.
  • Use NSDecimalNumber, which does exact decimal arithmetic.

Solution #1 requires you to convert between cents and dollars whenever you do input or output of monetary values, whereas solution #2 can be messier to code (e.g. you have to write something like [num1 decimalNumberByAdding:num2] instead of num1 + num2 to add two numbers).

I'd recommend solution #1, but go with whichever of those you think would work best.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 2
    +1 - Also, for a thorough understanding of why *not* to use a floating point type, see David Goldberg's classic "What Every Computer Scientist Should Know About Floating-Point Arithmetic": – Sherm Pendley Jun 14 '11 at 05:53
  • Also see this SO question: [Use float or decimal for accounting application](http://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount) – jscs Jun 14 '11 at 06:39
  • Sorry - surrounding it with <>s works everywhere else... :-( http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html – Sherm Pendley Jun 20 '11 at 04:22