Why is longLongValue returning the incorrect value

前端 未结 3 512
时光说笑
时光说笑 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:42

    I'm not sure if your are interested in a simple solution or just looking into the details of why the loss of precision takes place.

    If you are interested in a simple answer: -[NSDecimalNumber description] products a string with the value, and -[NSString longLongValue] converts a string into a long long

    NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:@"4937446359977427944"];
    long long longLongNumber = [[decimalNumber description] longLongValue];
    NSLog(@"decimalNumber %@ -- longLongNumber %lld", decimalNumber, longLongNumber);
    

    outputs

    2014-04-16 08:51:21.221 APP_NAME[30458:60b] decimalNumber 4937446359977427944 -- longLongNumber 4937446359977427944
    

    Final Note

    [decimalNumber descriptionWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]] may be more reliable is your app supports multiple locales.

提交回复
热议问题