双重限制字符

时间:2011-08-11 15:08:25

标签: iphone objective-c xcode

如何只使用两位小数来显示双精度数?当前代码如下(但当然,它显示了很多小数位):

    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 个答案:

答案 0 :(得分: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 

.precision说明符中f表示小数点后要打印的位数。

答案 1 :(得分:2)

更改此

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

到这个

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