Search code examples
objective-ccocoa-touchcore-datansnumbernsdecimalnumber

I'm using NSDecimalNumber in a method that works out a total price and sometimes it returns only one number after decimal when two are intended


I've have a method that loops through my core data fetched objects array and uses the price of each item and the quantity to work out the total price. It seems to work most of the time returning for e.g. 23.44, 3.65 but I've noticed that sometimes it will return for example 63.1 like below.

enter image description here

Here is my method:

+ (NSDecimalNumber *)totalPriceOfItems:(NSManagedObjectContext *)managedObjectContext
{
    NSError *error = nil;
    NSDecimalNumber *totalPrice = [[NSDecimalNumber alloc] initWithInt:0];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"BagItem"];

    // Get fetched objects and store in NSArray
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (BagItem *bagItem in fetchedObjects) {
        NSDecimalNumber *price = [[NSDecimalNumber alloc] initWithDecimal:[[bagItem price] decimalValue]];
        NSDecimalNumber *quantity = [[NSDecimalNumber alloc] initWithInt:[[bagItem quantity] intValue] + 1];

      NSDecimalNumber *priceFromQuantity = [price decimalNumberByMultiplyingBy:quantity];

      totalPrice = [totalPrice decimalNumberByAdding:priceFromQuantity];
      NSLog(@"total: %@", totalPrice);
    }

    return totalPrice;
}

Am I doing something wrong here?

Haven't had much experience using NSDecimalNumber but hopefully someone can help me figure this out.

Thanks for your time.


Solution

  • You can simply achieve that with the help of String Format Specifiers something like:

    NSLog(@"total: %.2f", [totalPrice floatValue]);
    

    or

    [NSString stringWithFormat:@"%.2f", [totalPrice floatValue]]
    

    %.2f which simply means two decimal places after the "."