2011-08-11 119 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:@"%f", tipPercentDbl]; 

这个

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

如果你想有完全两位小数即使值有'%.2f'会做工作“没有数字后点”正好。例如:'stringWithFormat:@“%。2f”,(double)8'将输出** 8.00 **。也许你的意思是相反的:如果你*不希望后缀零输出整数? – lxt

+1

@lxt:你说得对。我混淆了一些东西。我删除了这部分。 – dasdom

2

你想%.2f

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

格式符采取以下形式:

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

其中.precisionf的情况下表示小数点后要打印的位数。