Floating point numbers do not very well indicate specific numbers. Using double will make this happen less often, but you will still have a problem. For a technical description of how floating point numbers are stored (and why we have this problem in the first place), see this wikipedia article: IEEE 754-1985 . (Basically, floats are stored as a binary representation of a value and have only so many bits, so they quickly end and round to the nearest value that they can represent.)
Usually you donโt worry about +/-. 0000001 and just format them when you want to display them to the user with the corresponding number of decimal points, and he will be rounded. Inside, it does not matter how it is stored.
For example, if you want to display "result", you can do something like this:
float myFloat = 32 + 32.1; NSString *result = [NSString stringWithFormat:%@"%.2f", myFloat];
If you don't want a fixed number of decimal points, you can also use the floating point to NSNumber
:
float myFloat = 32 + 32.1; NSNumber *myNumber = [NSNumber numberWithFloat:myFloat]; NSString *result = [myNumber stringValue];
NSDecimalNumber
will take care of all this for you, but it NSDecimalNumber
little more involved and includes more overhead, but here is an example to get you started:
NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:@"32"]; NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:@"32.1"];
source share