Convert a string with mathematical expressions into a float

前端 未结 4 878
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 17:39

A text field contains mathematical expressions like: 12+45-6 Is possible to convert this string to a number?

Can we use the predicate facility?

相关标签:
4条回答
  • One solution that doesn't rely on external libraries is to first convert the string into a sequence of tokens, then evaluate the expression using the shunting-yard algorithm chained onto a simple stack machine.

    0 讨论(0)
  • 2021-01-16 17:55

    You need to parse this input using a parser then evaluate it. I have heard of people having success using muParser for this, to save you writing it all yourself. Check it out. http://muparser.sourceforge.net/

    0 讨论(0)
  • 2021-01-16 17:55

    Yes, of course it's possible.

    You should look into infix to postfix conversion using a stack: http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm

    And then look into how to evaluate a postix expression, also using a stack: http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm

    0 讨论(0)
  • 2021-01-16 18:04

    Yes. Read up on "expression evaluation", or use a ready-made script interpreter. JavaScript is available to all iOS programs as a part of WebView.

    0 讨论(0)
提交回复
热议问题