Re: working with NSDecimalNumber and NSNumber
Re: working with NSDecimalNumber and NSNumber
- Subject: Re: working with NSDecimalNumber and NSNumber
- From: Derrick Bass <email@hidden>
- Date: Sat, 24 Jun 2006 17:01:36 -0500
On Jun 23, 2006, at 10:34 AM, email@hidden wrote:
Hi list
I was wondering what was the most efficient way to process
calculations between an NSNumber and an NSDecimalNumber
should I use :
NSNumber *myNormalNumber;
NSDecimalNumber *myDecimalNumber;
[...]
myDecimalNumber = [myDecimalNumber decimalNumberByMultiplyingBy:
[NSDecimalNumber decimalNumberWithString:[myNormalNumber
stringValue]]];
or
myDecimalNumber = [myDecimalNumber decimalNumberByMultiplyingBy:
[NSDecimalNumber decimalNumberWithDecimal:[myNormalNumber
decimalValue]]];
(documentation says that decimalValue's value returned isn’t
guaranteed to be exact for float and double values)
Right, that's because floats and doubles are base-2 while
NSDecimalNumber is base-10. Now it is possible to represent any
base-2 value exactly as an decimal number, but NSDecimalNumber
doesn't have enough precision to be able to do that always for
doubles. Moreover, it is likely that whatever is in your float or
double is rounded off already. You won't get any more precision by
converting to strings (less, I should think). If you really need to
multiply by a non-integer float or double, there's really nothing to
be done; you'll just have to accept the precision loss.
or should I use parent methods From NSNumber like numberWithFloat: ?
I use NSDecimalNumber for money related values so my calculations
need to be as precise as possible ...
Are you sure you aren't actually multiplying by a decimal number? If
so, then you should represent it exactly in an NSDecimalNumber. If
your numbers really are floats (like from an interest calculation)
then you'll have to decide upon an appropriate rounding scheme. And
if it really is a decimal number, but you just can't help the fact
that it is represented by a float/double, then convert it to an
NSDecimalNumber and round it to the correct number of places before
calculating with it.
Derrick
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden