Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert between a C double and Cocoa's NSDecimalNumber?

I'm converting an algorithm I wrote in Java to Objective-C. In java the BigDecimal class handles base-10 numbers and can take the primitive double as a constructor arg. In Cocoa's NSDecimalNumber class, however, there is no direct way to construct an instance using a primitive double.

Currently I'm using this (smelly) hack:

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

Is there a better way?

like image 617
Mike Reedell Avatar asked Jan 04 '09 23:01

Mike Reedell


3 Answers

NSNumber, the superclass of NSDecimalNumber, has a +numberWithDouble: method. That's what you want.

like image 146
Chuck Avatar answered Sep 22 '22 17:09

Chuck


You can also use [[NSDecimalNumber alloc] initWithDouble:(double)], it's just not as obvious.

like image 32
Echilon Avatar answered Sep 18 '22 17:09

Echilon


[NSDecimalNumber numberWithDouble:myDouble]
like image 37
Sophie Alpert Avatar answered Sep 20 '22 17:09

Sophie Alpert