0

I am creating a application where users will enter speeds of a car in two textFields, Press the button and the app will tell you which car is faster. I'm aware that in order to do so, you need to use NSNumberFormatter but do I put the code in a separate method that compares the number and call on it when the button is clicked?

Dharmesh Kheni
  • 67,254
  • 32
  • 154
  • 160
Muhammad
  • 109
  • 1
  • 8

3 Answers3

1

Try:

NSDecimal *scannerValue = [NSDecimalNumber zero];
[[NSScanner scannerWithString:[textFieldInstance stringValue]] scanDecimal:scannerValue];
if ([scannerValue decimalValue] != [NSDecimalNumber zero]) { // got a number
} else { // not a number
}

The methods available are documented here with links to the class hierarchy. If you should need further help, do leave a comment.

hd1
  • 30,506
  • 4
  • 69
  • 81
  • Hmm, what would be the benefit of using this instead of, say, using `NSCharacterSet` to validate that the text is a number and then using `floatValue`? – rebello95 Dec 13 '14 at 04:57
1

First of all you should restrict the UITextFields for Decimal only values. Refer THIS for the same.

Then you can do something like following:

-(IBAction)fasterCar:(id)sender {

    int result = [self.txtField1.text intValue]; - [self.txtField1.text intValue];

    if (result > 0)              
         NSLog(@"1st one is faster");
    else if (result < 0)         
         NSLog(@"2nd one is faster);
    else                         
         NSLog(@"Both cars have equal speed");
}

Might seem old school, works well.

Community
  • 1
  • 1
Anon
  • 623
  • 3
  • 10
  • i like the old school method but I am still getting an error. I have the labels declared as - (IBAction)carSpeed1:(id)sender; - (IBAction)carSpeed2:(id)sender; do i need to write arguments for these too? – Muhammad Dec 13 '14 at 23:42
  • Those two you specified are not labels at all... They are IBActions. – Anon Dec 14 '14 at 05:24
  • but don't you need to connect the labels to the IBAction so the text changes? – Muhammad Dec 17 '14 at 23:30
0

Try like this in your button action method below:-

-(IBAction)calculateSpeed:(id)sender
{
    NSDecimalNumber *first=[NSDecimalNumber decimalNumberWithString:self.txt.text];
    NSDecimalNumber *second=[NSDecimalNumber decimalNumberWithString:self.txt2.text];
    (second > first) ? NSLog(@"Mclaren is faster") : NSLog(@"BMW is faster");
}
Hussain Shabbir
  • 13,963
  • 4
  • 34
  • 53