19

我正在开发一个 iPhone 应用程序,并希望代表货币 ($) 金额。我不能使用浮点数,因为它们会引入一定数量的舍入误差。我可以使用什么?

我正在考虑在内部定义我自己的 Money 类并将美元和便士存储为 NSInteger。

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

另一种可能的表示(更容易加法和乘法)是使用单个 NSInteger 作为便士。

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

你觉得呢?你有没有什么想法?我可以使用“BigDecimal”类型吗?

4

2 回答 2

27

使用 NSDecimalNumber。当然它有开销,但除非你能证明这是一个问题,否则你会喜欢它给你的准确性。

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

于 2009-05-06T16:20:41.773 回答
8

使用NSDecimalNumber类。

于 2009-05-06T16:19:26.270 回答