问题描述
我正在构建一个需要对金钱进行计算的应用.
I'm building a app that needs to perform calculations on money.
我想知道如何正确使用 NSDecimalNumber,尤其是如何从整数、浮点数和双打?
I wonder how to properly use NSDecimalNumber, especially how to initialize it from integers, floats & doubles?
我只发现使用 -decimalNumberWithString:
方法很容易.不鼓励使用 -initWith...
方法,因此只留下带有尾数的方法,但在我之前使用的 7 种语言中的任何一种中,我都不需要它,所以我不知道那里放了什么...
I only found it easy to use the -decimalNumberWithString:
method. The -initWith...
methods are discouraged so that only left the ones with mantissa, but never in any of 7 languages I used before did I need that so I don't know what put there...
推荐答案
Do NOT 使用 NSNumber
的 +numberWith...
方法创建 NSDecimalNumber
对象.它们被声明为返回 NSNumber
对象,并且不能保证作为 NSDecimalNumber
实例运行.
Do NOT use NSNumber
's +numberWith...
methods to create NSDecimalNumber
objects. They are declared to return NSNumber
objects and are not guaranteed to function as NSDecimalNumber
instances.
这在 Bill 的 thread 中有解释Bumgarner,苹果公司的一名开发人员.我鼓励您针对此行为提交错误,参考错误 rdar://6487304.
This is explained in this thread by Bill Bumgarner, a developer at Apple. I would encourage you to file a bug against this behavior, referencing bug rdar://6487304.
作为替代,这些是用于创建 NSDecimalNumber
的所有适当方法:
As an alternative these are all of the appropriate methods to use to create an NSDecimalNumber
:
+ (NSDecimalNumber *)decimalNumberWithMantissa:(unsigned long long)mantissa
exponent:(short)exponent isNegative:(BOOL)flag;
+ (NSDecimalNumber *)decimalNumberWithDecimal:(NSDecimal)dcm;
+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numberValue;
+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numberValue locale:(id)locale;
+ (NSDecimalNumber *)zero;
+ (NSDecimalNumber *)one;
+ (NSDecimalNumber *)minimumDecimalNumber;
+ (NSDecimalNumber *)maximumDecimalNumber;
+ (NSDecimalNumber *)notANumber;
如果您只是想要 float
或 int
常量中的 NSDecimalNumber
,请尝试以下操作:
If you simply want an NSDecimalNumber
from a float
or int
constant try something like this:
NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithDecimal:
[[NSNumber numberWithFloat:2.75f] decimalValue];
这篇关于如何使用 NSDecimalNumber?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!