2013-01-04 88 views
0

我有一個有多個數字和運算符的字符串轉換爲浮點數並計算

@"5+4-9/10"

如何從中得到結果?

我想在我使用的計算器內使用它。當按下數字或操作符時,我將不得不動態顯示結果。

我使用了arity jar文件android。但我不能在iPhone中實現類似的功能。

+0

您的解決方案將是 [這裏](https://github.com/davedelong/DDMathParser) – Sumanth

+0

當您選擇號碼,必須將數字從nsstring轉換爲int或float,如你所願.. –

+0

對於簡單的表達式,你可以使用'NSExpression',參見eg http://stackoverflow.com/a/12500518/1187415。否則,請使用適當的數學表達式解析器。 –

回答

9

這個什麼 -

NSString *formula = @"1+5*6"; 
NSExpression *exp = [NSExpression expressionWithFormat:formula]; 
NSNumber *resultForCustomFormula = [exp expressionValueWithObject:nil context:nil]; 
NSLog(@"%f", [resultForCustomFormula floatValue]); 

編輯: 現在我想到了你的要求,並提出使用NSScanner的方法你不會相信我沒有用之前NSScanner建議Mr. Borrrden我使用它,我發現它很棒。請參閱下面的方法 -

-(NSMutableString *)formatString:(NSString *)formula 
{ 
    // Let's check if there any wrong (.) value exm: 1/.2 or .7+3 
    // 1/0.2 and 0.7+3 are okay but above are incorrect so first fix them 

    NSString *str = formula; 
    NSInteger c = 0; 
    for(int i=0; i<[str length]; i++) 
    { 

     if([[NSString stringWithFormat:@"%c",[str characterAtIndex:i]] isEqualToString:@"+"] || 
      [[NSString stringWithFormat:@"%c",[str characterAtIndex:i]] isEqualToString:@"-"] || 
      [[NSString stringWithFormat:@"%c",[str characterAtIndex:i]] isEqualToString:@"/"] || 
      [[NSString stringWithFormat:@"%c",[str characterAtIndex:i]] isEqualToString:@"*"]) 
     { 
      if([str length] > i+1) 
      { 
       if([[NSString stringWithFormat:@"%c",[str characterAtIndex:i+1]] isEqualToString:@"."]) 
       { 
        formula = [formula stringByReplacingCharactersInRange:NSMakeRange(i+1+c, 1) withString:@"0."]; 
        c++; 
       } 
      } 
     } 
    } 

    // Now we will convert all numbers in float 

    NSString *aString; 
    float aFloat; 
    NSMutableString *formattedString = [[NSMutableString alloc]init]; 

    NSScanner *theScanner = [NSScanner scannerWithString:formula]; 
    while ([theScanner isAtEnd] == NO) 
    { 

     if([theScanner scanFloat:&aFloat]) 
     { 
      [formattedString appendString:[NSString stringWithFormat:@"%f",aFloat]]; 
     } 

     if([theScanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&aString]) 
     { 
      [formattedString appendString:aString]; 
     } 
    } 
    return formattedString; 
} 

這將(2.222 /。4)+ 9999-7 + 0.7 * 0.13在轉換爲(2.222000/0.400000)+ 9999.000000-7.000000 + 0.700000 * 0.130000
只需在使用NSExpression之前調用此方法即可。

NSString *formula = @"(2.222/.4)+9999-7+0.7*.13"; 
NSString *formattedString = [self formatString:formula]; 
NSExpression *exp = [NSExpression expressionWithFormat:formattedString]; 
NSNumber *resultForCustomFormula = [exp expressionValueWithObject:nil context:nil]; 
NSLog(@"Result = %f", [resultForCustomFormula floatValue]); 

//OutPut: Result = 9997.646484 

注:我不是說,將在所有的公式字符串的工作。可能在某些情況下它不起作用。但它將在一般方程中起作用。

+0

我得到的地板價值。我試過7/4和它的返回1.0000 –

+0

是啊,因爲7和4是整數,所以你肯定會得到1.0000嘗試它與浮動像7.0/4.0然後看:) – TheTiger

+0

是否有方法來驗證表達式,因爲我想動態地顯示結果 –

3

Note that :您必須通過至少一個浮點值

我知道這不是最好的方式,但是像這樣的東西可以爲你工作。

NSString *formula = @"5+4-9/10"; 
NSString *str = [formula lastPathComponent]; 
formula = [formula stringByReplacingOccurrencesOfString:str withString:[NSString stringWithFormat:@"%@.0",str]]; 
NSString *strCal=[NSString stringWithString:formula]; 
NSExpression *exp=[NSExpression expressionWithFormat:strCal]; 
float result=[[exp expressionValueWithObject:nil context:nil] floatValue]; 
NSLog(@"result:%f",result); 

您可以使用GCMathParserDDMathParser

不知道這是否是最有效的方法,但寫過無論如何幫助你...... !!!

+3

您不需要虛擬「NSPredicate」,請參閱http://stackoverflow.com/a/12500518/1187415。 –

+0

我收到警告「NSPredicate可能不會迴應左表達式」 –

+0

雅@MartinR,我只是編輯我的問題 – Bhavin

0

你可以解析 「全部」 數字飄起:

NSMutableString *numericExpression = [NSMutableString stringWithString:@"4+3/2-7/4"]; 

NSMutableString *nExp=[NSMutableString stringWithString:@""]; 
BOOL innum=false; 
BOOL dotfound=false; 

for (NSInteger charIdx=0; charIdx<numericExpression.length; charIdx++){ 
     NSString *substr=[NSString stringWithFormat:@"%C",[numericExpression characterAtIndex:charIdx]]; 
     if (isdigit([numericExpression characterAtIndex:charIdx])) { 
      // in number 
      innum=true; 
     }else if ([substr isEqualToString:@"."]){ 
      // dot found ... 
      innum=true; 
      dotfound=true; 
     }else{ 
      // not in number 
      if (innum && dotfound) { 
       NSLog(@"all good (*).*"); 
      }else if(innum && !dotfound){ 
       NSLog(@"adding .0"); 
       [nExp appendString:@".0"]; 
      } 
      innum=false; 
      dotfound=false; 
     } 
    [nExp appendString:substr]; 
    NSLog(@"%@",nExp); 
} 

NSExpression *expression = [NSExpression expressionWithFormat:nExp]; 
NSNumber *result = [expression expressionValueWithObject:nil context:nil]; 
NSLog(@"calc %@ = %@",nExp,result);