如何在Objective-C / iOS中代表钱? [英] How to represent money in Objective-C / iOS?

查看:86
本文介绍了如何在Objective-C / iOS中代表钱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款iPhone应用,想要代表金额($)金额。我不能使用float因为它们会引入一定量的舍入错误。
我可以使用什么?

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?

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

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;
}

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

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;
}

您有什么想法?我可以使用BigDecimal类型吗?

What are your thoughts? Is there a "BigDecimal" type I can use?

推荐答案

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

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

这篇关于如何在Objective-C / iOS中代表钱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆