0

I'm trying to find a way to calculate result from NSString. Is there a simple NSString calculator category?

NSString *str = @"10+20/2";
int result = [[str stringByCalculatingResult] intValue];
NSLog (@"result:%i", result);

Prefer output:

result:20

Thank you for solution.

Category:

//NSString+Calculator.h
@interface NSString (Calculator)
- (NSString*)stringByCalculatingResult;
@end

//NSString+Calculator.m
@implementation NSString (Calculator)
- (NSString*)stringByCalculatingResult
{
    NSExpression *expression = [NSExpression expressionWithFormat:self];
    NSNumber *value = [expression expressionValueWithObject:nil context:nil];
    return [value stringValue];
}
@end
rozochkin
  • 679
  • 1
  • 7
  • 18
  • what about using NSPredicate like this? http://stackoverflow.com/questions/8618005/how-to-convert-string-to-math-equation-in-objective-c – Alberto Vitale Jul 30 '13 at 13:47
  • possible duplicate of [How to evaluate the string equation in ios](http://stackoverflow.com/questions/16785873/how-to-evaluate-the-string-equation-in-ios) – Martin R Jul 30 '13 at 13:49
  • possible duplicate of [Objective-C Calculating string value](http://stackoverflow.com/questions/6072439/objective-c-calculating-string-value) – Daniel Jul 30 '13 at 13:50

2 Answers2

2

You should look at using the NSExpression class which can evaluate mathematical expressions for you:

NSExpression *expression = [NSExpression expressionWithFormat:@"10 + 20 / 2"];
id value = [expression expressionValueWithObject:nil context:nil];
Wain
  • 118,658
  • 15
  • 128
  • 151
0

You can take a look at this mathematical parser library

zahreelay
  • 1,742
  • 12
  • 18