2011-08-11 4 views
0

소수점 이하 두 자리로만 이중을 표시하려면 어떻게합니까?두 자로 제한되는 문자

tipPercentDbl = 20;//tipPercent as Dbl 
    tipDbl = (totalDbl * (tipPercentDbl/100));//tip as Dbl 
    tip.text = [NSString stringWithFormat:@"%f", tipDbl]; 
    tipPercent.text = [NSString stringWithFormat:@"%f", tipPercentDbl]; 
    totalWithTipDbl = (totalDbl+tipDbl); 
    totalWithTip.text = [NSString stringWithFormat:@"%f", totalWithTipDbl]; 

답변

2

변경하면 값이있는 경우에도 정확히 두 개의 소수를 원한다면이

tipPercent.text = [NSString stringWithFormat:@"%.2f", tipPercentDbl]; 
+1

tipPercent.text = [NSString stringWithFormat:@"%f", tipPercentDbl]; 

'%의 .2f'이 일을 할 것'없이 숫자 점 후 ' 잘 됐네. 예 :'stringWithFormat : @ "%. 2f", (double) 8'은 ** 8.00 **을 출력합니다. 아마도 당신은 반대를 의미합니다 : * 후미 0을 정수로 출력하지 않기를 원한다면? – lxt

+1

@lxt : 네 말이 맞아. 나는 뭔가를 섞어. 이 부분을 삭제했습니다. – dasdom

2

당신은 %.2f 원하는 :

%[flags][width][.precision][length]specifier 
:

tip.text = [NSString stringWithFormat:@"%.2f", tipDbl]; 
tipPercent.text = [NSString stringWithFormat:@"%.2f", tipPercentDbl]; 
// ... 
totalWithTip.text = [NSString stringWithFormat:@"%.2f", totalWithTipDbl]; 

형식 지정자의 형태를 취할 현재 코드는 다음과 같이 (그러나 물론, 그것은 소수 자릿수를 많이 보여주는 것)입니다

여기서 지정자의 경우 .precision은 소수점 뒤에 인쇄 할 자릿수를 의미합니다.

관련 문제