doubleValue does not convert the object to a double value correctly at all times

爷,独闯天下 提交于 2020-01-04 06:35:21

问题


I have an NSArray in which I would like to store double values. I defined it as follow

NSMutableArray *setOfDoubles;

I add the elements as follow

NSNumber *num;
num = [NSNumber numberWithDouble:someDouble];
[setOfDoubles addObject:num];

And I read the element as follow

num = [setOfDoubles lastObject];  
[setOfDoubles removeLastObject];
doubleValueToUse = [num doubleValue];

My problem is sometimes (Not always), for example when num (as an object) is 5.1, doubleValueToUse (as a double value) is 5.099999999999996. The way I figured num (as an object) is 5.1 is that I debug and when I am hovering the mouse on top of num on the line num = [setOfDoubles lastObject]; it shows 5.1 but after doubleValue conversion it becomes the number I mentioned. Does anybody know why is this happening?


回答1:


Not every number can be accurately represented using a float variable. For example, you can't precisely represent, say, 1/3 using a finite number of digits in our common decimal (base-10) system, but in ternary (base-3), it would be just 0.1. Similarly, the numbers you can write with a finite number of digits in decimal, may not necessarily have the finite number of digits in their binary representation, hence the error.

A few links on the topic if you are interested:

http://floating-point-gui.de/basic/

http://www.mathworks.com/support/tech-notes/1100/1108.html

http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html




回答2:


This is normal for float values.

If you want to save initial (same) representation of float numbers in all places of your code, you can save them, for example, in NSString. When you will need float number you will just write [NSString floatValue];. But it is not effective if you have large amount of float values.



来源:https://stackoverflow.com/questions/7286133/doublevalue-does-not-convert-the-object-to-a-double-value-correctly-at-all-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!