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

て烟熏妆下的殇ゞ 提交于 2020-01-24 04:32:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23892130/how-to-get-floating-point-number-from-the-nsexpressions-expressionvaluewithobje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!