Search code examples
iosobjective-cnsdecimalnumber

Remove negative symbol (-) from NSDecimalNumber gives me an error


I have an array with NSDecimalNumbers inside. I will do a check to see if that number is a negative number. If it is, I want to remove the negative sign (-). Here is my code:

NSString *amount = [myArray objectAtInde:2]; // Is a NSDecimalNumber with value of: -397.67

    if ([amount doubleValue] < 0) {
        amount = [amount stringByReplacingOccurrencesOfString:@"-" withString:@"- $"];
    }

When I do that, I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSDecimalNumber stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x7fcaf94eff80'

Solution

  • Try this,

    NSDecimalNumber *amountNumber = [myArray objectAtIndex:2]; // Is a NSDecimalNumber with value of: -397.67
    
    NSString *stringWithDollarSymbol = [self addDollarSymoblForNumber:amountNumber];
    

    You can assign the stringWithDollarSymbol to label

    - (NSString *)addDollarSymoblForNumber:(NSDecimalNumber *)decimalNum
    {
        NSString *modifiedString = @"";
        if (decimalNum) {
            NSString *numberInStringForm = [decimalNum stringValue];
                if ([decimalNum doubleValue] < 0) { //adds dollor symbol for negative numbers
                modifiedString = [numberInStringForm stringByReplacingOccurrencesOfString:@"-" withString:@"- $"];
            }
            else //adds dollor symbol for positive numbers
            {
                modifiedString = [NSString stringWithFormat:@"$ %@",modifiedString];
            }
        }
        return modifiedString;
    }
    

    EDIT

    More Better Approach using NSNumberFormatter:

    - (NSString *)formatNumberBasedOnCurrentLocale:(NSDecimalNumber *)number
    {
        NSNumberFormatter *formatter = [[NSNumberFormatter  alloc] init];
        [formatter setLocale:[NSLocale currentLocale]];
        [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        NSString *result = [formatter stringFromNumber:number];
        if (result.length >0) {
            return result;
        }
        return nil;
    }