"Dynamic" display of floats?
I'm trying to write an app for iphone in ObjectiveC. I need to display a statustext that tells the user the value of a few variables. These values are 开发者_开发技巧changeable by dragging a marker with your finger in a diagram. The problem I have is that the value range is quite wide. If you want to set values between 0 and 1 you probably want 3 decimals (like 0.345). But if the range is 0 to 10000, you don't need any decimals at all.
I now have about 20 diffrent messages that can be displayed and if I want all of them to display values "dynamically" there is going to be a lot of code like this:
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;
}
Is there not a better way to do it?
Use an NSNumberFormatter
. This is what it's for.
Build your format string with a format string.
NSString* MyFormatString = [NSString stringWithFormat:@"Start :%%.%df Stop :%%.%df",
numberOfDecimals,
numberOfDecimals];
[NSString stringWithFormat:MyFormatString, start, stop]; break;
In case anyone cares, this is what I came up with after consulting the docs for 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 ]]];
Not sure if it's the most elegant or efficient solution but it works and looks better.
Simple. Replace the switch
statement with:
lblStatus.text = [NSString stringWithFormat:@"Start: %.*f Stop :%.*f", numberOfDecimals, start, numberOfDecimals, stop];
精彩评论