Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get floating point number from the NSExpression's expressionValueWithObject:context method?

I have already implemented a custom calculator where I am using following code to evaluate the arithmetic expression something like 5+3*5-3.

- (NSNumber *)evaluateArithmeticStringExpression:(NSString *)expression {

    NSNumber *calculatedResult = nil;

    @try {
        NSPredicate * parsed = [NSPredicate predicateWithFormat:[expression stringByAppendingString:@" = 0"]];
        NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
        calculatedResult = [left expressionValueWithObject:nil context:nil];
    }
    @catch (NSException *exception) {

        NSLog(@"Input is not an expression...!");
    }
    @finally {

        return calculatedResult;
    }
}

But when I am having integers with division operation I am getting only integer as a result. Let's say for 5/2 I am getting 2 as a result. It's right for the shake of programming because of the integer division.

But I need floating point result.

How can I get it rather scanning the expression string and replace the integer divisor as a floating point. In our example 5/2.0 or 5.0/2.

like image 749
Goppinath Avatar asked May 27 '14 14:05

Goppinath


1 Answers

I found it by myself.

- (NSNumber *)evaluateArithmeticStringExpression:(NSString *)expression {

    NSNumber *calculatedResult = nil;

    @try {
        NSPredicate * parsed = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"1.0 * %@ = 0", expression]];
        NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
        calculatedResult = [left expressionValueWithObject:nil context:nil];
    }
    @catch (NSException *exception) {

        NSLog(@"Input is not an expression...!");
    }
    @finally {

        return calculatedResult;
    }
}

it's simply start the expression with the operand "1.0 * " and everything will be floating point calculation onwards.

NSPredicate * parsed = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"1.0 * %@ = 0", expression]];

NB: Thanks @Martin R but, my question wasn't about integer division, it's totally about NSExpression. I have clearly excluded with my last sentence.

@Zaph, Exception handling is used here for a strong reasons. It is a place where my method is accepting user input wehre user can enter something like w*g and - expressionValueWithObject: context: will throw an exception and I have to avoid the abnormal termination of my App. If the user entered a valid expression then he/she will get an answer in the form of NSNumber otherwise a nil NSNumber object.

like image 50
Goppinath Avatar answered Nov 03 '22 16:11

Goppinath