0

I want to evaluate a string which is written in JavaScipt in iOS and learned I can to that by using: [self.webView stringByEvaluatingJavaScriptFromString:formula]

The code I'm using is:

NSString *formula = @"( 1.5 * Math.pow(2, 3) ) / 12"; formula = [NSString stringWithFormat:@"eval('%@')", formula]; NSInteger value = [[self.webView stringByEvaluatingJavaScriptFromString:formula] integerValue];

The problem is the Math.pow function. If I dont use it , I get a real value form the webView. If I have Math.pow in the string, I just get empty string back. Can anyone help me how to change the code so I can use strings which contains Math.pow?

4
  • did you try to wrap that into javascript method and execute f.e [[self.webView stringByEvaluatingJavaScriptFromString:@"javascript:myMethod();"] in your js method execute needed calculations and print output number Commented May 30, 2014 at 7:39
  • 1
    why do you need that -> you can execute such calculations natively Commented May 30, 2014 at 7:47
  • Im not too good with JS so how would that code look like? Commented May 30, 2014 at 7:48
  • I get the string from a server which only can send JS :S Commented May 30, 2014 at 7:48

1 Answer 1

1

The problem is here:

NSInteger value = [[self.webView stringByEvaluatingJavaScriptFromString:formula] integerValue];

where you are converting your result in a integer value. So, it gets rounded off.

Correct would be:

float value = [[self.webView stringByEvaluatingJavaScriptFromString:formula] floatValue];

notice both the value type and the use of floatValue for the conversion from string.

BTW, you do not need the eval, strictly.

Sign up to request clarification or add additional context in comments.

2 Comments

This has no effect on the JS result which is an empty string @"".
In my case it is working, I tested it before posting. If I use 24 instead of 12, I get 0.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.