如何在 obj-c 中打印带有参数位数的格式化浮点数



我知道使用特定数字设置格式化浮点的方法

NSLog(@"%.2f", myFloat);

设置参数编号的方法是什么?像这样的东西

cell.lblOpenPrice.text = [NSString stringWithFormat:@"%.%if", trade.open_price, trade.digits];

为此,您应该使用 NSNumberFormatter 的实例。有几十种选择,太多了,无法在这里讨论。即您可以设置总位数(有效数字(或整数和小数位数,如此处所述。

NSNumberFormatter *formatter = [NSNumberFormatter new];
// Do the desired configuration
NSString *text = [formatter stringFromNumber:@(myFloat)];

若要动态设置字段精度,请在格式中使用星号并首先提供精度参数,因此代码示例为:

cell.lblOpenPrice.text = [NSString stringWithFormat:@"%.*f", trade.digits, trade.open_price];

相关内容

最新更新