Currently I am pulling data from a webservice and populating the data into a custom object.

I am storing decimals such as 4.56 etc.

I am slightly confused by NSDecimal and NSDecimalNumber. I have read that NSDecimalNumber should be used when dealing with money, which I am. So the question is whether or not my properties should be NSDecimal or NSDecimalNumber. I have read cases where your model would be NSDecimal and that you would use NSDecimalNumber for any arithmetic with the numbers.

I basically want to create behavior like such in ObjectiveC

private decimal thirtyYear;

public decimal getThirtyYear(){
    return thirtyYear/100.0;
}

public void setThrityYear(decimal rate){
    thirtyYear = rate;
}

So, should my thirtyYear property be NSDecimal or NSDecimalNumber. Also, when doing the dividing within the getThirtyYear() method should I use NSDecimalNumber for the arithmetic.

有帮助吗?

解决方案

Question #1: Should my thirtyYear property be NSDecimal or NSDecimalNumber?

As you stated if you're dealing with any financial calculations always use NSDecimalNumber and NSDecimalNumber provides predictable rounding behavior and precision when performing base 10 calculations.

If you want more detailed information this is from the Apple Documentation directly:

NSDecimalNumber is an immutable subclass of NSNumber that provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10 exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer between -128 and 127.

Now in regards to NSDecimal, this is a C struct and not as easy to work with in Objective C. As stated above that's where the NSDecimalNumber object comes in which is made to work with object oriented languages. In short NSDecimalNumber is the way to go. It is easier to work with.

Question #2: When dividing within the getThirtyYear() method should I use NSDecimalNumber for the arithmetic?

If precision calculations are crucial in your app then yes use NSDecimalNumber since they're guaranteed to be accurate.

Since you will be using NSDecimalNumber I suggest checking out the NSDecimalNumber Class Reference because the class has a number (no pun intended) of useful methods. Hope this helps.

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