I'm calculating back and forth some values and that's where I get the problem. Let's say you have a yearly amount of 100 Dollar and save them as as monthly value to CoreData using decimalnumbers:

[self.sumPerMonth decimalNumberByAdding:[amount decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:@"12"]]];

Ok so my 100 Dollars are now 8.33333333333333.... Now in some places in my app I want to get the value back to yearly. So if I calculate now 12*8.33333333 I don't get 100 but something very close: 99.999999999999999999999999999999999996.

For a progress bar I'm doing this and this results in 100% which is what I actually want (moneySpent being 100 and budget being 99.999999999999999999999999999999999996):

[[moneySpent decimalNumberByDividingBy:budget] doubleValue]

But if I'm doing this (budgetLeft being budget-moneySpent):

[budgetLeft compare:[NSDecimalNumber zero]] == NSOrderedAscending

This results in TRUE, which is wrong. With currencies this should be 0 because 99.999999...6 should be 100.

So how would you handle this? I'm a bit confused...should I only compare using doubleValues? Or should I always round the NSDecimalNumbers or what?

有帮助吗?

解决方案

You can use the decimalNumberByRoundingAccordingToBehaviour: method of NSDecimalNumber whenever you need to round back to 'currency'. The NSDecimalNumberBehaviours protocol allows you to specify the rounding mode and the scale (decimal places) - so you can round to two decimal places whenever you need an actual currency amount - typically at the end of any calculations.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top