Limit Characters in Double
How can I make a double appear with only two decimal places? Current code is as follows (but of course, it's showing a lot of decimal places):
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 stringWi开发者_StackOverflowthFormat:@"%f", totalWithTipDbl];
Change this
tipPercent.text = [NSString stringWithFormat:@"%f", tipPercentDbl];
to this
tipPercent.text = [NSString stringWithFormat:@"%.2f", tipPercentDbl];
You want %.2f
:
tip.text = [NSString stringWithFormat:@"%.2f", tipDbl];
tipPercent.text = [NSString stringWithFormat:@"%.2f", tipPercentDbl];
// ...
totalWithTip.text = [NSString stringWithFormat:@"%.2f", totalWithTipDbl];
Format specifiers take the form of:
%[flags][width][.precision][length]specifier
where .precision
in the case of f
specifiers means the number of digits to be printed after the decimal point.
精彩评论