1

First time using NSDecimalNumber, so I've wondered do I really need to create so many objects? In my method I want to calculate monthly costs out of daily costs. The monthly costs are stored in self.sumPerMonth and the parameter costs is the daily cost value. So I want to add to my monthly costs 30 * costs. Is this the easiest way to do that?

[self.sumPerMonth decimalNumberByAdding:[costs decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"30"]]];
Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
MichiZH
  • 5,587
  • 12
  • 41
  • 81

2 Answers2

2

NSDecimalNumber is immutable so yes, you need to create a new object each time you do an operation.

The clumsiness of dealing with the objects is the compromise you make for getting base-10 calculations without loss of precision and with predictable rounding behavior.

Beware of mixing NSNumber and NSDecimalNumber.

A little reading: http://rypress.com/tutorials/objective-c/data-types/nsdecimalnumber.html

Community
  • 1
  • 1
occulus
  • 16,959
  • 6
  • 53
  • 76
1

Yes, that's the way to go using NSDecimalNumber.

If there's valid reason to be concerned about number of objects created you could switch to the plain NSDecimal struct type. The difference is that NSDecimal is mutable.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • @MichiZH It means that the value of a `NSDecimalNumber` can't be changed, whereas the value of an `NSDecimal` can. – Nikolai Ruhe Jan 27 '14 at 09:52
  • Ok so my way of calculating is okay like this? I mean the objects not needed anymore will be deleted anyway right? – MichiZH Jan 27 '14 at 09:52
  • @MichiZH As I said, your code is fine. Everything will be cleaned up. – Nikolai Ruhe Jan 27 '14 at 09:53
  • Ok thx. One last question: I've used double before (shame on me :-) with currencies in coredata. I've calculated the sum of relationsships like this: [self.hasTransactions valueForKeyPath:@"@sum.amount"]. Can I do this as well with the Decimal type? – MichiZH Jan 27 '14 at 09:56