0

I have been trying to get some basic math done with NSExpression's expressionValueWithObject(), and the results have been inconsistent.

For example, the following all work just fine:

NSExpression(format: "1+1").expressionValueWithObject(nil, context: nil) as? Float

(returns 2)

NSExpression(format: "1+1.2").expressionValueWithObject(nil, context: nil) as? Float

(returns 2.2)

NSExpression(format: "2**3").expressionValueWithObject(nil, context: nil) as? Float

(returns 8)

NSExpression(format: "sqrt(2**3)").expressionValueWithObject(nil, context: nil) as? Float

(returns 2.82...)

NSExpression(format: "log(2**3)").expressionValueWithObject(nil, context: nil) as? Float

(returns 0.903...)

But other string-equations, seemingly no more complex than these, produce erroneous answers or no answers at all. For example,

NSExpression(format: "1+(1/2)").expressionValueWithObject(nil, context: nil) as? Float

(returns 1, rather than 1.5)

and

NSExpression(format: "43 % 2").expressionValueWithObject(nil, context: nil) as? Float

(returns an error, though Swift itself can natively compute 43 Mod 2 using that same notation)

What am I doing wrong in these last two examples?

Michael Stern
  • 479
  • 3
  • 13

1 Answers1

1

The built-in binary operators supported by NSExpression are limited. % is not supported. Here's a possible solution from this question:

NSExpression(format: "modulus:by:(43,2)").expressionValueWithObject(nil, context: nil) as? Float

1+(1/2) is unsurprisingly calculated with integer division. Using 1+(1/2.0) returns 1.5.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • If my inputs are coming in a string, and the input is "1+(1/2)", is there some way I can force floating point math without editing the string? – Michael Stern Oct 02 '15 at 17:48
  • I doubt it... this seems like a misuse of NSExpression. How about parse it yourself? :) http://funwithobjc.tumblr.com/post/6196535272/parsing-mathematical-expressions – jtbandes Oct 02 '15 at 18:00
  • If I have to, I have to, but that will be a big project for me as a beginner to Swift, and the source code you link to may not help much, as I don't know Objective C. Thanks for the pointer. – Michael Stern Oct 02 '15 at 20:11