Objective c &引用;“动态”;浮标的显示?

Objective c &引用;“动态”;浮标的显示?,objective-c,ios,floating-point,floating-accuracy,Objective C,Ios,Floating Point,Floating Accuracy,我正在尝试用Objective为iphone编写一个应用程序。我需要显示一个statustext,告诉用户一些变量的值。这些值可以通过在图表中用手指拖动标记来更改。 我的问题是,这个值的范围很宽。如果要将值设置为0到1之间,可能需要3位小数(如0.345)。但是如果范围是0到10000,则根本不需要任何小数 我现在有大约20条不同的消息可以显示,如果我想让它们都“动态”显示值,将会有很多这样的代码: float start,stop; // Defined earlier... switc

我正在尝试用Objective为iphone编写一个应用程序。我需要显示一个statustext,告诉用户一些变量的值。这些值可以通过在图表中用手指拖动标记来更改。 我的问题是,这个值的范围很宽。如果要将值设置为0到1之间,可能需要3位小数(如0.345)。但是如果范围是0到10000,则根本不需要任何小数

我现在有大约20条不同的消息可以显示,如果我想让它们都“动态”显示值,将会有很多这样的代码:

float start,stop;    // Defined earlier...
switch ( numberOfDecimals ) {
    case 0:
        lblStatus.text = [NSString stringWithFormat:@"Start: %.0f  Stop :%.0f", start, stop];  break;
    case 1:
        lblStatus.text = [NSString stringWithFormat:@"Start: %.1f  Stop :%.1f", start, stop];  break;
    case 2:
        lblStatus.text = [NSString stringWithFormat:@"Start: %.2f  Stop :%.2f", start, stop];  break; 
    default:  break;
} 

没有更好的方法吗?

使用格式字符串构建格式字符串

NSString* MyFormatString = [NSString stringWithFormat:@"Start :%%.%df Stop :%%.%df",
        numberOfDecimals,
        numberOfDecimals];
[NSString stringWithFormat:MyFormatString, start, stop];  break; 

使用
NSNumberFormatter
。这就是它的用途。

如果有人关心,这就是我在查阅NSNumberFormatter文档后得出的结论:

float start,stop; 
NSNumberFormatter *formatter;

// Setup the formatter
formatter = [[NSNumberFormatter alloc] init]; 
[formatter setNumberStyle:NSNumberFormatterDecimalStyle ];
[formatter setMaximumFractionDigits: numberOfDecimals ];

lblStatus.text = [NSString stringWithFormat:@"Start: %@  Stop:%@", 
                  [formatter stringFromNumber: [NSNumber numberWithFloat: start]], 
                  [formatter stringFromNumber: [NSNumber numberWithFloat: stop ]]];  

不确定这是不是最优雅或最有效的解决方案,但它确实有效,而且看起来更好

简单。将
开关
语句替换为:

lblStatus.text = [NSString stringWithFormat:@"Start: %.*f  Stop :%.*f", numberOfDecimals, start, numberOfDecimals, stop];