0

Not exactly sure what it would be called?

But anyway, I am wondering how exactly one would make a calculator where the user types his equation into a text box, and then when the user hits "=" it calculates everything the user has typed in.

ex. user types: 1 + 1 * (1 +2) hits enter 6 (is displayed)

-EDIT- I screwed up on my math :P 4 (is displayed)

I couldn't find any articles talking about this on the internet, for I didn't really know what to search for. So if anyone could help, or at least point me in the right direction. It would be greatly appreciated.

Thanks, Regards.

Neil
  • 2,004
  • 3
  • 23
  • 48

4 Answers4

3

These are called math parsers.

There are two very good libraries that are freely available: DDMathParser and GCMathParser.

See this question for more details.

They are much more capable than NSExpression.

Community
  • 1
  • 1
lnafziger
  • 25,760
  • 8
  • 60
  • 101
  • 2
    DDMathParser is the method I am using now. It is simple to use and works amazingly. Also it is free: check out the wiki here for all question concerning it: https://github.com/davedelong/DDMathParser/wiki/Usage – Neil Mar 16 '12 at 23:45
2

What you are looking for is something with NSExpression I think:

NSExpression *expression = [NSExpression expressionWithFormat:inputText, nil];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];

I have tested NSExpression with mathematical symbols (0-9, +, -, *, /, (, )) and it seems to work as expected. Give it a shot, it may just work for you.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • Thanks I think this is exactly what I'm looking for, I'll try it out. Then let you know – Neil Mar 15 '12 at 00:28
  • This is really awesome, but the `+ expressionWithFormat` isn't documented in the NSExpression Class Reference. Is there any info on how it works (or is it a private class)? – lnafziger Mar 15 '12 at 16:05
  • @Inafziger no, it isn't a private method, but god only knows why apple doesn't have it documented in the latest version of their docs. It used to be documented, but I'm not sure why it wouldn't be anymore. – Richard J. Ross III Mar 15 '12 at 16:13
  • Very strange! Great functionality though! – lnafziger Mar 15 '12 at 23:06
1

You might try looking up "infix notation" and "parse trees" as a start.

user1118321
  • 25,567
  • 4
  • 55
  • 86
1
1 + 1 * (1 +2) hits enter 6 (is displayed)

hmm, i'm sure there're lot of samples of human math, but 1 + 1x(1+2) != 6 :)

One recommendation from me would be to collect all unrecognized character-groups and consider it to be variables, then let a user to enter the values. Like 1 + y*(1+z), enter, y=1, z=2, enter, result=4.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
A-Live
  • 8,904
  • 2
  • 39
  • 74