如何只使用两位小数来显示双精度数?当前代码如下(但当然,它显示了很多小数位):
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];
答案 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];