-2

I am building a calculator, and I have the following:

firstOperand = @"2883"
secondOperand = @"10"
operator = @"/" // division

How would I get the result here as an NSString? Here is how I would do the equivalent in Python:

result = str (float(firstOperand) / float(secondOperand))

How would I do the same in Obj-C?

David542
  • 104,438
  • 178
  • 489
  • 842
  • I highly recommend looking at official documentation. And after that, if you still can't find the answer to something so rudimentary, try searching on SO. – nhgrif Aug 30 '14 at 20:35
  • Also, read the answers to this question: http://stackoverflow.com/questions/13007001/what-is-the-use-of-nsexpression – jlehr Aug 30 '14 at 21:20

1 Answers1

1

Yo have two ways to do so. If your string only contains the number and you are certain it is "well-written" you can just use

int i = [yourString intValue];

or floatValue, or doubleValue or integerValue ...

If your string is not well formatted, and you need something more powerful to extract the data, you need to use [NSNumberFormatter][1]. For instance:

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* number = [formatter numberFromString:yourString];

Code is ARC.

Instances of NSNumberFormatter format the textual representation of cells that contain NSNumber objects and convert textual representations of numeric values into NSNumber objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position. NSNumberFormatter objects can also impose ranges on the numeric values cells can accept.

Jean
  • 7,623
  • 6
  • 43
  • 58
  • There's also `integerValue`, `doubleValue`, `longLongValue`, and `boolValue`... but ultimately, this question is a duplicate. – nhgrif Aug 30 '14 at 20:37
  • Indeed. I should have guessed such question was already asked. Based on David542's reputation, I thought he would have checked first... – Jean Aug 30 '14 at 20:39
  • It's a good thought... but it appears he got all that rep via [tag:python] and has since forgotten how [so] works. – nhgrif Aug 30 '14 at 20:43