Reputation: 5228
I am adding two floats like:
NSString *val1=@"355.00";
NSString *val2=@"55555550.00";
NSString *result=[NSString stringWithFormat:@"%.2f",[val1 floatValue]+[val2 floatValue]];
The answer i am getting is 55555908.00 while on calculator it is 55555905.00
What i am doing wrong?
Upvotes: 1
Views: 968
Reputation: 540125
As already stated in the comments, this is a floating point precision problem.
A float
has a precision of about 7 decimal digits, a double
about 15 decimal digits.
The Foundation framework also provides the NSDecimalNumber
class for doing base-10 arithmetic, with a precision of 38 decimal digits:
NSString *val1 = @"355.00";
NSString *val2 = @"55555550.00";
NSDecimalNumber *dec1 = [NSDecimalNumber decimalNumberWithString:val1];
NSDecimalNumber *dec2 = [NSDecimalNumber decimalNumberWithString:val2];
NSDecimalNumber *decsum = [dec1 decimalNumberByAdding:dec2];
NSString *result = [decsum stringValue];
// --> 55555905
Upvotes: 5
Reputation: 8029
See: float vs. double precision
Floating point numbers in C use IEEE 754 encoding.
This type of encoding uses a sign, a significand, and an exponent.
Because of this encoding, you can never guarantee that you will not have a change in your value.
Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.
Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.
Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.
Upvotes: 2