Question

I have an array that stores textfield.text input. I then retrieve the text elsewhere as a float. This seems to give me the “exact number” from the text field.

Example A

   navtestAppDelegate *appDelegate = 
   (navtestAppDelegate *)[[UIApplication 
    sharedApplication] delegate];

NSMutableArray *storedData = 
 appDelegate.myData;

[storedData replaceObjectAtIndex: myIndex withObject: mytextfield.text];

float number = [[storedData objectAtIndex:myIndex] floatValue];

if mytextfield.text input is 22.8, float number returns 22.8

however,

Example B

[storedData replaceObjectAtIndex: myIndex withObject: @"22.8”];

float number  = [[storedData objectAtIndex:myIndex] floatValue];

float number returns 22.7999999

I don't understand why I get the exact number in example A

Was it helpful?

Solution

The value 22.8 can not be represented in binary floating point exactly. What you are seeing is a representation based on the display format. Different display methods may use different display formats. Displaying different number of digits and the rounding means that both 22.8 and 22.7999999 are correct for the number of digits displayed after rounding. Note that 22.7999999 was displayed and not 22.8000000 because the next digit was 2 so the value displayed was rounded down.

This is base dependent, that is things that can be exact in one number base may not be able to be exact in a different number base. In this case 22.8 in the decimal number base can not be exact in the binary number base.

This is the reason that NSDecimal exists and the reason floating point is not used for monetary values.

This is somewhat equivalent to displaying the value of pi in base decimal, the number of digits is infinite so for every display someone decided how many digits to show. Interestingly, pi can be represented exactly (but usefully) in the pi number base. :-)

In the case of float and double there is a finite number of digits that can be represented.

OTHER TIPS

Try like this:-

[storedData replaceObjectAtIndex: myIndex    
 withObject: [NSNumber 
 numberWithFloat:22.8]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top