Setting decimal places for an object in the Dictionary


#1

I have a question about NSLog results.

The code: (It’s basically a brute force attempt to add the required types for the plist. Still need to add NSData.)

[code]
int main(int argc, const char * argv[])
{

@autoreleasepool {
    
    NSMutableArray *stocks = [[NSMutableArray alloc] init];
    
    NSMutableDictionary *stock;
    
    stock = [NSMutableDictionary dictionary];
    [stock setObject:@"AAPL" forKey:@"symbol"];
    [stock setObject: [NSNumber numberWithInt:200] forKey:@"shares"];
    [stock setObject:[NSDate date] forKey:@"date"];
    [stock setObject: [NSNumber numberWithFloat:1.23] forKey:@"arbitrary float"];
    [stock setObject:[NSNumber numberWithBool:YES] forKey:@"arbitrary answer"];
    [stocks addObject:stock];
    
    stock = [NSMutableDictionary dictionary];
    [stock setObject:@"GOOG" forKey:@"symbol"];
    [stock setObject: [NSNumber numberWithInt:160] forKey:@"shares"];
    [stock setObject:[NSDate date] forKey:@"date"];
    [stock setObject: [NSNumber numberWithFloat:4.56] forKey:@"arbitrary float"];
    [stock setObject:[NSNumber numberWithBool:NO] forKey:@"arbitrary answer"];
    [stocks addObject:stock];
    
    [stocks writeToFile:@"/tmp/stocks.plist" atomically:YES];
    
    NSArray *stockList = [NSArray arrayWithContentsOfFile:@"/tmp/stocks.plist"];
    
    for (NSDictionary *d in stockList) {
        NSLog(@"I have %@ shares of %@, it's %@, here's an arbitrary number %@ and an arbitrary answer %@", [d objectForKey:@"shares"], [d objectForKey:@"symbol"], [d objectForKey:@"today"], [d objectForKey:@"arbitrary float"], [d objectForKey:@"arbitrary answer"]);
    }
    
}
return 0;

}[/code]

The result:

I have 200 shares of AAPL, it’s 2012-08-19 05:35:32 +0000, here’s an arbitrary number 1.230000019073486 and an arbitrary answer 1
I have 160 shares of GOOG, it’s 2012-08-19 05:35:32 +0000, here’s an arbitrary number 4.559999942779541 and an arbitrary answer 0

The question: can I truncate the float to 2 decimal places?

I tried to do “here’s an arbitrary number %.2@” but I get the warning message “Precision used with ‘@’ conversion specifier, resulting in undefined behavior”.

I tried “here’s an arbitrary number %.2f” and got the error message: “Conversion specifies type ‘double’ but the argument has type ‘id’”

Isn’t the object under the key “arbitrary float” a float? What does it mean that it has type ‘id’?