Search code examples
iphonexcodexcode4

How to put a decimal point according to the will of the user in a calculator in iphone?


I have a calculator in which i would like to put the decimal point according to the button press for the decimal point. I get the decimal point but if I enter another digit the decimal pint vanishes and is overwritten .

The code is mentioned below for the decimal press:-

-(IBAction)decimalPressed:(id)sender{
  calculatorScreen.text = [calculatorScreen.text stringByAppendingString:@"."];
}

For the digit press it is :-

-(IBAction)buttonDigitPressed:(id)sender{
  currentNumber = currentNumber*10 + (float)[sender tag];
  calculatorScreen.text = [NSString stringWithFormat:@"%g",currentNumber];
}

How can i do something like 23 then "." then 45. The result would be 23.45


Solution

  • I've recently done a calculator app and could understand your problem. Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well.

    With that said, you can use a IBAction (remember to link it to your storyboard or xib file)

    -(IBAction)decimalPressed:(UIButton *)sender
    {
     NSRange range = [self.display.text rangeOfString:@"."];
    if (range.location ==NSNotFound){
    self.display.text = [ self.display.text stringByAppendingString:@"."];
    }
    self.userIsInTheMiddleOfEnteringANumber = YES;
    }
    

    While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes

    you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code.

    NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "." therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:@".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display.

    userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own.