Convert NSNumber to NSDecimalNumber
20,351
Solution 1
You can do:
NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithDecimal:[aNumber decimalValue]];
Solution 2
So:
NSNumber * number = [NSNumber numberWithInt:10];
NSDecimalNumber *d = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];
And in Swift
let number = NSNumber(int: 10)
let dec = NSDecimalNumber(decimal: number.decimalValue)
Author by
Michael Rivers
Updated on July 09, 2022Comments
-
Michael Rivers almost 2 years
I realize that NSDecimalNumber inherits from NSNumber.
However, I am struggling to figure out how I can init an NSDecimalNumber from an NSNumber or how to convert an NSNumber to an NSDecimalNumber.
I have tried
NSDecimalNumber* d = [aNumber copy];
where
aNumber
is an NSNumber object to no avail.Am I missing something?
Thanks.
-
rmaddy over 10 yearsThe 2nd one isn't valid (and in both cases
d
needs to be a pointer). -
Michael Rivers over 10 yearsOnly problem is that passing an NSNumber with value of 2e+34 ends up with decNum of 2 and 34 zeros. would like it to maintain the same mantissa and exponent.
-
rmaddy over 10 years
2e+34
is 2 with 34 zeros. Those are the same number expressed in two different ways. -
pronebird over 8 years@rmaddy what are you talking about?
-
rmaddy over 8 years@Andy The answer has been edited twice (as of this comment) since my original comment. Look at the edit history to see what the answer looked like at the time of my comment.