English 中文(简体)
Cast as an NSNumber doubleValue adding extra [phantom] precision
原标题:

iPhone sdk 3.2.1

 NSMutableDictionary *myDict = [NSMutableDictionary dictionaryWithCapacity:2];
 [myDict setObject:[NSNumber numberWithDouble:0.1f] forKey:@"testDoubleObject"];
 [myDict setValue:[NSNumber numberWithDouble:0.1f] forKey:@"testDoubleValue"];

Printing the description of myDict to the console yields this:

Printing description of myDict: {type = mutable, count = 2, capacity = 3, pairs = ( 0 : {contents = "testDoubleObject"} = {value = +0.10000000149011611938, type = kCFNumberFloat64Type} 1 : {contents = "testDoubleValue"} = {value = +0.10000000149011611938, type = kCFNumberFloat64Type} )}

Pulling the doubles back out of the dict shows these phantom digits are being preserved:

 NSNumber *doubleFromObject = [myDict objectForKey:@"testDoubleObject"];
 NSNumber *doubleFromValue = [myDict valueForKey:@"testDoubleValue"];

Printing doubleFromObject and doubleFromValue yields this in the console:

Printing description of doubleFromObject: {value = +0.10000000149011611938, type = kCFNumberFloat64Type}

Printing description of doubleFromValue: {value = +0.10000000149011611938, type = kCFNumberFloat64Type}

The same thing happens when I try to create an NSNumber doubleValue from a string:

 NSString *doubleAsAString = @"0.1";
 NSNumber *doubleAsANumber = [NSNumber numberWithDouble:[doubleAsAString doubleValue]];

Printing doubleAsANumber yields this in the console:

Printing description of doubleAsANumber: {value = +0.10000000000000000555, type = kCFNumberFloat64Type}

These extra phantom digits are causing me problems.

1) What is causing this to happen?

2) How can I get rid of those extra phantom digits?

问题回答

1. What is causing this to happen?

These "phantom" digits as you say are the by-product of representing a base-10 number in base-2.

2. How can I get rid of those extra phantom digits?

The best way to get rid of them would be to use a fixed-precision type, such as NSDecimal.





相关问题
Code sign Error

I have created a new iPhone application.I have two mach machines. I have created the certificate for running application in iPhone in one mac. Can I use the other mac for running the application in ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

将音频Clips从Peter改为服务器

我不禁要问,那里是否有任何实例表明从Peit向服务器发送音响。 I m不关心电话或SIP风格的解决办法,只是一个简单的袖珍流程......

• 如何将搜查线重新定位?

我正试图把图像放在搜索条左边。 但是,问题始于这里,搜索条线不能重新布署。

热门标签