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

1

5

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.

Belted answered 27/5, 2014 at 14:28 Comment(3)
In Objective-C exceptions are reserved for programming errors, not control flow.Coseismal
Compare https://mcmap.net/q/2031907/-nsexpression-1-2.Immoderacy
One option is to pass in floating point numbers: "5.0/2.0".Coseismal
B
9

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.

Belted answered 28/5, 2014 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.