Convert between C double and Cocoa NSDecimalNumber?

I am converting an algorithm written in Java to Objective-C. In java, the BigDecimal class handles base-10 numbers and can take a primitive double as the arg constructor. However, in the Cocoa NSDecimalNumber class, there is no direct way to instantiate using a primitive double.

I am currently using this (smelly) hack:

    [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%1.38f", number]];

Is there a better way?

+5
source share
5 answers

NSNumber, a superclass of NSDecimalNumber, has a method + numberWithDouble :. Is this what you want.

+15
source

You can also use [[NSDecimalNumber alloc] initWithDouble:(double)], this is not so obvious.

+5
source
[NSDecimalNumber numberWithDouble:myDouble]
+3

, .

    NSNumber *temp = [NSNumber numberWithDouble:self.hourlyRate];
    myDecimal = [NSDecimalNumber decimalNumberWithDecimal:[temp decimalValue]]; 

, .

+2

In other posts, I find information that using methods NSNumberwith NSDecimalNumbereither will return NSNumberor will return NSDecimalNumber, but it is not that the specification says that it is so that it can be considered errors and changes in the future. Something like that.

0
source

All Articles