問題代碼
label1.text = [NSString stringWithFormat:@"%2.f", num]; // 錯誤格式
格式字串解析
%2.f:總寬度 2,小數點後 0 位 → 等同 %.0f 但最小寬度 2,數值 < 0.5 顯示為 0
%.2f:小數點後 2 位(標準金額格式)
%f:預設小數點後 6 位
修正
label1.text = [NSString stringWithFormat:@"%.2f", num]; // 保留兩位小數
label2.text = [NSString stringWithFormat:@"%.2f", cost];
label3.text = [NSString stringWithFormat:@"%.2f", costft];
進階:NSNumberFormatter(區域化、貨幣符號)
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
fmt.numberStyle = NSNumberFormatterDecimalStyle;
fmt.minimumFractionDigits = 2;
fmt.maximumFractionDigits = 2;
label.text = [fmt stringFromNumber:@(num)];
常見格式對照
| 格式 | 輸入 3.14159 | 輸入 0.3 |
%2.f | 3 | 0 |
%.2f | 3.14 | 0.30 |
%f | 3.141590 | 0.300000 |