Search code examples
iosobjective-cnsarray

NSArray of doubles iOS (Objective c)


In my array I have this data, each value is type double:

(
    "28.04234",
    "29.3234",
    "25.03324",
    "9.390000000000001",
)

And I need to change all elements to NSString only with 2 decimal how can I do this with the best approach optimizing code.

For example:

myArray[0] = "28.04"
myArray[1] = "29.32"

....


Solution

  • In swift you could do this with a map statement. In Objective-C you must have an NSArray of NSNumbers. It's not possible to have an NSArray of a value type like double in Objective-C. (It is possible - normal, even - to have a C array of floating point values, but I don't think that's what you're talking about.)

    Try code like this:

    NSArray <NSString *>*mapArrayOfNumbers(NSArray <NSNumber *> *sourceArray) {
        NSMutableArray *result = [NSMutableArray arrayWithCapacity: sourceArray.count];
        for (NSNumber *aNumber in sourceArray) {
            [result addObject:[NSString stringWithFormat: @"%.02f", aNumber.doubleValue]];
        }
        return result;
    }
    

    And you could call it like this:

    NSArray <NSNumber *> *numbers = @[@(1.1), @(2.2), @(3.4567), @(8.901234), @(9.876543)];
    NSArray <NSString *> *strings = mapArrayOfNumbers(numbers);
    for (NSString *aString in strings) {
        NSLog(@"Entry = %@", aString);
    }