Question

I have an interesting situatin to solve, its more like a quiz :)

I have to recreate a simple calculator and I have two buttons with up/down on it. The function of this two buttons are simpe, they take the current value and it sums 1 or take 1. So I manage to create a small function that convert the value into a string and in case of 34.1, I create the new value of 0.1 to add or subtract.

- (float)findFloatValueToAdd:(NSString *)aString
{
  NSMutableString *val = [NSMutableString stringWithCapacity:aString.length];

  for (int i = 0; i < aString.length; i++)
    [val appendFormat:@"0"];

  if ([aString rangeOfString:@"."].location != NSNotFound)
    [val replaceCharactersInRange:NSMakeRange([aString rangeOfString:@"."].location, 1)
                       withString:@"."];

  [val replaceCharactersInRange:NSMakeRange(aString.length-1, 1)
                     withString:@"1"];

  return [val floatValue];
}

The main problem is when I have lot of decimals like 23.1234212. If I have to go up it jumps direct to 23.12342, down the same. If i continue to go down from 23.12342, it goes to 23.12341 > 23.1234 but then it goes to 23.1233>23.1232>23.1231...

So, how can I truly solve this problem?

thanks guys!

Was it helpful?

Solution

As one of the comments says this does sound a bit like homework... Two ideas for you to explore:

1) How are you displaying the result? If you don't know what a format such as %5.2f means then find out - look up format specifications. This may explain the apparent truncation, however...

Do exactly what you want is tricky using numbers. Computers use base-2 arithmetic and floating-point has a limited range of accurate digits - unlike mathematics. If that doesn't make sense consider the fraction 1/3, what is its decimal representation? 0.333333333 ad nasuem. A value in one representation may not have an exact equivalent in another, and this is the same for a decimal number you write and its representation in binary floating point by the computer. So:

2) Your code starts with a string representation of a floating point number, which appears to be limited to digits and a decimal point - i.e. no exponent. You then create a string of the number you wish to add. Then you convert to floating point and things start to go wrong. Why convert to floating point at all? You could do this all with strings. Starting with the last character (rightmost), look it up and "add" one - so if it's '1' you want a '2', if the character is a '9' you want a '0' and a "carry" of 1. Now move to the next character...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top