Reputation: 1587
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?
Upvotes: 5
Views: 5098
Reputation: 19
In other posts I'm finding info that using the NSNumber
methods with NSDecimalNumber
either will return NSNumber
, or will return NSDecimalNumber
but that's not what the spec says it should so it may be considered a bug and change in the future. Er something like that.
Upvotes: 0
Reputation: 10244
You can also use [[NSDecimalNumber alloc] initWithDouble:(double)]
, it's just not as obvious.
Upvotes: 5
Reputation: 4180
I've found the way to get this to work, and to dismiss the warning is like this.
NSNumber *temp = [NSNumber numberWithDouble:self.hourlyRate];
myDecimal = [NSDecimalNumber decimalNumberWithDecimal:[temp decimalValue]];
It gets rid of the warning, albeit being two lines instead of one.
Upvotes: 2
Reputation: 237040
NSNumber, the superclass of NSDecimalNumber, has a +numberWithDouble: method. That's what you want.
Upvotes: 14