Set NSDecimal to zero

2.2k views Asked by At

What are the different ways of setting a NSDecimal to zero? I'm not keen on any of the 3 I found so far.

NSDecimal zero = {0}; // Not obvious what's going on here.

NSDecimal zero = @(0).decimalValue; // @(0) appears to always return the same instance.

NSDecimal zero = [NSDecimalNumber zero].decimalValue; // [NSDecimalNumber zero] appears to always return the same instance.

Is there one that is most accepted than others? Am I missing some kind of NSDecimalZero constant/function?

3

There are 3 answers

7
Sulthan On BEST ANSWER

I have never noticed that NSDecimal doesn't have a nice Create function.

I can't imagine another method than the 3 you list.

NSDecimal zero = {0};

You are right, this is not obvious, this is actually very far from obvious. Usual programmers won't look up the documentation to see what value the struct will represent with all attributes set to zero.

NSDecimal zero = @(0).decimalValue

I don't like it because it uses NSNumber and needlessly creates an autoreleased object.

NSDecimal zero = [NSDecimalNumber zero].decimalValue

This is my preferred solution. Using NSDecimal structs directly is done mostly for performance boosts (without creating objects on the heap). This method matches the intent because it uses a singleton constant.

However, if you have a lot of code involving NSDecimal and performance is really important for you, create your own function/macro to initialize the struct and use this function everywhere. Then this problem won't matter to you because the function name will make the code obvious.

4
Anoop Vaidya On

I guess you need to use NSDecimalNumber,

Typically we do as:

NSDecimalNumber *zeroDecimal = [[NSDecimalNumber alloc] initWithFloat:0.f];

NSDecimal zero = @(0).decimalValue; // @(0) appears to always return the same instance.

NSDecimal zero = [NSDecimalNumber zero].decimalValue; // [NSDecimalNumber zero] appears to always return the same instance.

Above two returns equivalent value of 0.0, first one is just the shorthand notation for the second one. You boxed 0 to NSDecimalNumber, using new syntax.


However, NSDecimal is typedefStruct that looks like this

typedef struct {
    signed   int _exponent:8;
    unsigned int _length:4;     // length == 0 && isNegative -> NaN
    unsigned int _isNegative:1;
    unsigned int _isCompact:1;
    unsigned int _reserved:18;
    unsigned short _mantissa[NSDecimalMaxSize];
} NSDecimal;
3
JeremyP On

NSDecimal is a C struct which you are not supposed to look inside (you can but you shouldn't) so that rules out the first which is technically looking inside the struct.

Either of the second two are absolutely fine. Note that, in C, assigning to a struct copies all the fields, so although [NSDecimalNumber zero] always returns the same object, your NSDecimal will be a unique struct and changing its contents won't affect any other NSDecimal that has been "created" in the same way.