How to represent money in Objective-C / iOS?

穿精又带淫゛_ 提交于 2019-12-12 09:33:39

问题


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

I'm 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?


回答1:


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




回答2:


Use the NSDecimalNumber class.



来源:https://stackoverflow.com/questions/830369/how-to-represent-money-in-objective-c-ios

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