如何从NSExpression的expressionValueWithObject:context方法中获取浮点数?

Gop*_*ath 5 floating-point objective-c ios nsexpression

我已经实现了一个自定义计算器,我使用下面的代码来计算像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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我使用除法运算的整数时,结果只得到整数.让我们说5/2我得到2结果.由于整数除法,它适合于编程的动摇.

但我需要浮点结果.

我怎样才能得到它而不是扫描表达式字符串并将整数除数替换为浮点.在我们的示例5/2.0或5.0/2中.

Gop*_*ath 8

我自己找到了.

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它只是用操作数"1.0*"启动表达式,一切都将是浮点计算.

NSPredicate * parsed = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"1.0 * %@ = 0", expression]];
Run Code Online (Sandbox Code Playgroud)

NB:谢谢@Martin R但是,我的问题不是关于整数除法,而是完全关于NSExpression.我的最后一句话明显被排除在外.

@Zaph,这里使用异常处理是有充分理由的.这是我的方法接受用户输入的地方,用户可以输入类似w*g和 - expressionValueWithObject:context:将抛出异常,我必须避免我的应用程序的异常终止.如果用户输入了有效的表达式,那么他/她将以NSNumber的形式获得答案,否则将获得nil NSNumber对象.