Which objective-c type is appropriate for handling money?

我怕爱的太早我们不能终老 提交于 2019-12-06 18:00:18

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6339120/which-objective-c-type-is-appropriate-for-handling-money

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!