doubleValue does not convert the object to a doubl

2019-07-21 03:32发布

问题:

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.