Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic math problem with Integer and NSDecimalNumber - Invalid operands to binary

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.

like image 893
Slee Avatar asked Aug 24 '10 17:08

Slee


2 Answers

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];
like image 157
falconcreek Avatar answered Sep 22 '22 00:09

falconcreek


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.

like image 42
shosti Avatar answered Sep 19 '22 00:09

shosti