2010-12-14 2 views
1

저는 객관적인 C/iPad 개발을위한 초보자입니다.하지만 iPad에서 간단한 4 가지 함수 계산기를 만들려고합니다.Objective C에서 NSString stringWithFormat을 사용하여 소수점 표시

현재 가장 큰 어려움은 소수점 버튼을 누를 때 .으로 표시됩니다. 다음은 두 개와 같은 버튼을 누를 때 일어나는 일입니다. 단지

display = display*10+. 

을하려고

-(IBAction)inTwo:(id)sender { 
    display = display*10+2; 
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];  
} 

분명히 작동하지 않습니다. 디스플레이 끝까지 마침표를 추가하는 방법은 무엇입니까? 이 문자열이 아닌 이후

감사

+0

숫자를 출력 형식으로 지정하려면 일반적으로 NSNumberFormatter를 사용해야합니다. –

+1

'resultfield'에서 그냥 치고, 편리한 DDMathParser를 통해 실행하십시오 : http://github.com/davedelong/DDMathParser –

답변

0
resultfield.text = [result.text stringByAppendingString:@"."]; 

당신은,하지만 display에 점을 추가 할 수 없습니다. 당신은 단지 그것을 표시하려면

1

당신은이 작업을 수행 할 수 있습니다

[resultField setText:[NSString stringWithFormat:@"%f%@", display, @"."]]; 

을 그런 다음 다른 방법으로, 그들을 추가하기 전에 소수점이 있는지 확인했다 :

-(IBAction)inTwo:(id)sender { 
    if([resultField.text rangeOfString:@"."] == NSNotFound) { 
     display = display*10+2; 
     [resultfield setText:[NSString stringWithFormat:@"%f",display]]; 
    } 
    else { 
     display += 2/10 * (resultField.length - [resultField.text rangeOfString:@"."] +1) 
     [resultfield setText:[NSString stringWithFormat:@"%f",display]]; 
    } 
} 

여기에서하는 일은 먼저 자릿수를 자릿수 또는 소수 자릿수에 추가해야하는지 확인하기 위해 소수점이 있는지 확인합니다. 소수점이 있으면 십진수의 위치와 전체 문자열의 길이 사이의 차이를 10 배로 나눈 숫자를 더합니다.

0

는 당신은 조금에 의해 그것을 놓친 :

어떤 이유로 파서가 F 플로트 또는 무언가의 정확성에 대한 지정의 일종으로 % 이후에 소수점을 식별하는 경우
[resultfield setText:[NSString stringWithFormat:@"%f.", display]]; 

(거의 긍정 적이 지 않습니다.) 소수점을 벗어나십시오 :

[resultfield setText:[NSString stringWithFormat:@"%f\.", display]]; 
0

나는 당신이 선택한 방식과 약간 다르게 할 것입니다. 나는 버튼을 디스플레이를 직접 업데이트하고 계산에 필요할 때만 숫자로 변환 할 것입니다.

, 그런데

-(double) displayAsDouble 
{ 
    NSDecimalNumber* displayAsDecimal = [NSDecimalNumber decimalNumberWithString: [resultField text]]; 
    return [displayAsDecimal doubleValue]; 
} 

NSDecimalNumber로 수를 떠나 고려 :

-(IBAction)inTwo:(id)sender 
{ 
    NSString* displayedText = [resultField text]; 
    [resultfield setText:[NSString stringByAppendingString: @"2"]]; 
} 

-(IBAction)inDecimal:(id)sender 
{ 
    if (![self isDecimalAlreadyPressed]) // only allowed one decimal in the number 
    { 
     NSString* displayedText = [resultField text]; 
     [resultfield setText:[NSString stringByAppendingString: @"."]]; // actually want the localised character really 
     [self setDecimalAlreadyPressed: YES]; 
    } 
} 

그런 다음 당신이 뭔가를 계산해야 할 때. NSDecimalNumber에는 간단한 산술 연산을위한 메소드가 있으며 10 진법을 사용하므로 부동 소수점 숫자로 성가신 표현 문제를 피할 수 있습니다.

관련 문제