Why is longLongValue returning the incorrect value

前端 未结 3 513
时光说笑
时光说笑 2021-01-20 11:01

I have a NSDictionary that contains a key with a value of 4937446359977427944. I try and get the value of it as a long long and get 4937446359977427968 back?



        
3条回答
  •  盖世英雄少女心
    2021-01-20 11:38

    For anyone interested in quick solution to the problem, as per Analog File proper answer:

    long long someNumber = 8204064638523577098;
    NSLog(@"some number lld:               %lld", someNumber);
    NSNumber *snNSNumber = [NSNumber numberWithLongLong:someNumber];
    NSLog(@"some number NSNumber:          %@", snNSNumber);
    NSString *someJson = @"{\"someValue\":8204064638523577098}";
    NSDictionary* dict = [NSJSONSerialization
     JSONObjectWithData:[someJson dataUsingEncoding:NSUTF8StringEncoding]
     options:0
     error:nil];
    NSLog(@"Dict: %@", dict);
    NSLog(@"Some digit out of dict:        %@", [dict objectForKey:@"someValue"]);
    NSLog(@"Some digit out of dict as lld: %lld", [[dict objectForKey:@"someValue"] longLongValue]);
    long long someNumberParsed;
    sscanf([[[dict objectForKey:@"someValue"] stringValue] UTF8String], "%lld", &someNumberParsed);
    NSLog(@"Properly parsed lld:           %lld", someNumberParsed);
    

    Results in:

    2014-04-16 14:22:02.997 Tutorial4[97950:303] some number lld:
    8204064638523577098

    2014-04-16 14:22:02.998 Tutorial4[97950:303] some number NSNumber:
    8204064638523577098

    2014-04-16 14:22:02.998 Tutorial4[97950:303] Dict: { someValue = 8204064638523577098; }

    2014-04-16 14:22:02.998 Tutorial4[97950:303] Some digit out of dict:
    8204064638523577098

    2014-04-16 14:22:02.999 Tutorial4[97950:303] Some digit out of dict as lld: 8204064638523577344

    2014-04-16 14:22:02.999 Tutorial4[97950:303] Properly parsed lld:
    8204064638523577098

提交回复
热议问题