Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSDecimalNumber?

Tags:

math

cocoa

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

like image 403
mamcx Avatar asked Jan 17 '09 17:01

mamcx


People also ask

What is NSDecimalNumber?

NSDecimalNumber , an immutable subclass of NSNumber , provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

What is NSNumber in Swift?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .


1 Answers

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]; 
like image 83
Ashley Clark Avatar answered Oct 04 '22 19:10

Ashley Clark