Man the simplest stuff always seems so crazy in Objective-C to me, anyways I need to do some basic subtraction and multiplication and am stumped.
I have:
client.PricingDiscount <-- this is an Integer 16 property on a CoreData NSManagedObject
sku.RetailPrice <-- this is a Decimal property on a CoreData NSManagedObject
I am simply trying to get a NSDecimalNumber to display like so:
NSDecimalNumber *showPrice = sku.RetailPrice * (100 - client.PricingDiscount);
I have tried a bunch of different forms of this and cannot figure out what the hell I am doing wrong here.
Standard operators cannot be used with NSDecimalNumber
NSDecimalNumber *one = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInt:100] decimalValue]];
NSDecimalNumber *factor = [one decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithDecimal:[client.PricingDiscount decimalValue]]];
NSDecimalNumber *showPrice = [sku.RetailPrice decimalNumerByMultiplying:factor];
NSDecimalNumber
is an object wrapper for a number--you are treating it like a C value. Instead, try:
float price = [sku.retailPrice floatValue] * (100 - [client.pricingDiscount floatValue]);
NSDecimalNumber *showPrice = [NSDecimalNumber numberWithFloat:price];
It's confusing, but NSNumber
and NSDecimalNumber
are Objective-C wrappers for C types, typically used for storage in container objects such as NSArray
(or Core Data). NSInteger
and NSDecimal
, on the other hand, are C types (NSInteger
just maps to int
).
EDIT: falconcreek's answer is better for avoiding accuracy loss. When working with integers, though, you'll typically use unboxed C types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With