-1

I have looked for an answer to this but could not find one. I am developing an iOS 7 Application that uses an Interest Rate. I have declared the following:

double InterestRate;
InterestRate = 3.9;

I set my button label to print Interest 3.9% and it works fine:

[btnInterest setTitle:[NSString stringWithFormat:@"Interest %.2f%%",InterestRate] forState:UIControlStateNormal];

Then when someone clicks on the button, I am sending this off to my PopOver Window like so:

if ([[segue identifier] isEqualToString:@"InterestController"])
{
    CC_InterestViewController *vc = [segue destinationViewController];
    vc.delegate = self;
    [vc setInterestRate:InterestRate];   <---- BREAKPOINT HERE!!!!! (See Below)
}

Which is received by my PopOver like so:

-(void)setInterestRate:(double)rate
{
    interestRate = rate;
}

I then pull the 3.9 into different parts, so I can seperate them into a UIPickerview using two columns to select an interest rate. The only problem is that I get:

3.89% NOT 3.9%

So, I put a breakpoint at the point I am sending the InterestRate to the PopOver from the Segue, and I find that iOS reports my 3.9 as 3.8999999999999.

I am specifically setting it to 3.9. Is there a better way of doing this? I have found that basically if I set the setting to 3.9, it will then be reported by iOS as 3.8999999999999.

Any Ideas?

-UPDATE:

Ok, this is marked as a duplicate. But, I am not using a float, but a double. Not sure if it makes much of a difference, but there doesn't seem to be an answer. If I declare double = 3.9, and then I look at the value it says it is 3.89999999999999. This is definitely not the same. So, my basic question is what is the best way to deal with this? I need 3.9 to always equal 3.9, not 3.89999999999999. If this is a duplicate question, how come the link does not give a simple straight forward answer as how to handle it, but a long winded explanation as to the problem. I know there is a problem. I am looking for an answer.

Bitco Software
  • 405
  • 1
  • 5
  • 15

1 Answers1

1

Its to do with the way doubles (i.e., floating point numbers) are stored (see this question for more information.).

If you want accurate results use a NSDecimalNumber. There are the basic methods (add, subtract, multiply, divide) for performing arithmetic.

NSDecimalNumber *interestRate = [NSDecimalNumber decimalNumberWithMantissa:39 exponent:-1 isNegative:NO];

To display a NSDecmialNumber as a string use a NSNumberFormatter.

Community
  • 1
  • 1
Rich
  • 8,108
  • 5
  • 46
  • 59