哪种 Objective-C 类型适合处理金钱?
哪种 Objective-C 类型适合处理金钱?我需要一些与核心数据兼容的东西。
Which objective-c type is appropriate for handling money? I need something which is Core Data compatible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种解决方案:
int
,并始终跟踪以美分为单位的货币价值(或您所使用的任何货币的最小可能除法)。仅使用整数计算。NSDecimalNumber
,执行精确的十进制算术。解决方案 #1 要求您在输入或输出货币值时在美分和美元之间进行转换,而解决方案 #2 的代码可能会比较混乱(例如,您必须编写类似
[num1decimalNumberByAdding:num2]
而不是num1 + num2
来添加两个数字)。我推荐解决方案#1,但请选择您认为最有效的解决方案。
There are two solutions:
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.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 ofnum1 + num2
to add two numbers).I'd recommend solution #1, but go with whichever of those you think would work best.