本文介绍了如何使用NSDecimalNumber?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个需要对钱进行计算的应用程序。



我想知道如何正确使用NSDecimalNumber,尤其是如何从整数,浮点数; doubles?



我发现很容易使用 -decimalNumberWithString:方法。不建议使用 -initWith ... 方法,以便只留下带尾数的方法,但从未使用之前使用的7种语言中的任何一种,所以我不需要 使用 NSNumber / code>' + numberWith ... 方法创建 NSDecimalNumber 对象。它们被声明为返回 NSNumber 对象,并且不能保证用作 NSDecimalNumber 实例。



这在此,由苹果公司的开发人员Bill Bumgarner负责。我建议你针对这种行为提出一个错误,引用错误rdar:// 6487304。



另一种方法是使用所有适当的方法创建一个 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;

如果你只想要一个 NSDecimalNumber float int 常数尝试这样:

  NSDecimalNumber * dn = [NSDecimalNumber decimalNumberWithDecimal:
[[NSNumber numberWithFloat:2.75f] decimalValue];


I'm building a app that needs to perform calculations on money.

I wonder how to properly use NSDecimalNumber, especially how to initialize it from integers, floats & doubles?

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 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.

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.

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;

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:22