简体   繁体   中英

Parse iOS-SDK - decimal number adding zeros

I have a list of Products in Parse, the format is like so;

{
    Environment = Both;
    "Ground_indoor" = Finished;
    "Ground_outdoor" = Finished;
    "Max_Working_Height" = "9.800000000000001";
    Name = "8m Battery Scissor Lift - Genie GS2632";
    "Non_Marking_Tyres" = 1;
    "Platform_Length" = "2.26";
    "Platform_Type" = "Scissor Lift";
    "Platform_Width" = "0.8100000000000001";
    "Tax_Class" = E;
    Weight = 1956;
}

However for some strange reason, anything with an "8" it's adding some random zeros in between. For example Platform_Width is actually;

http://puu.sh/mlGLo/be9f200472.png

Any clues?

Yes this is due to floating point inaccuracy. You may find very academic explanation about it here .

Or if that is too much to read, let's simply put it this way - for example, let's take the value 0.81 as an example. The number cannot be accurately represented by a float and is rounded up to 0.8100000000000001 because an int value of 81 is represented by the binary value 1010001. In order to make the value 0.81 it would be accurate if you could take 81 x 10^-2 (= 81 / 10^2.) But that's impossible because you must use the base 2 instead of 10. So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 81 (1010001) + 3 bits for the value 7 (111). Then the value 81 x 2^-7 is not seriously inaccurate. So to improve this inaccuracy, we could change the value 81 and 7 to something else. So the formula for your value would be X = A x 2^B where A and B are integer values positive or negative. The higher the numbers are the higher accuracy become. However as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

Hope this explains your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM