I know there’s a “hard” way to do that (not that hard, but not straight up).
I display a float value as a percentage in a label that way :
myLabel.text = [NSString stringWithFormat:@"%.1f%%", myFloat];
I want to force the label to display the sign of the float. Of course, it automatically shows the “-” if the value is negative. I know I can do that using a method of that type :
-(NSString *) stringFromFloat: (float) theFloat {
if (theFloat > 0) return [NSString stringWithFormat: @"+%.1f%%", theFloat];
else return [NSString stringWithFormat: @"%.1f%%", theFloat];
}
But that would imply calling [self stringFromFloat:aFloat]; every time I need to display the float value. I know using this solution is “better” because it lowers the number of re-used lines, but if my labels don’t all show the same number of decimals, the stringFromFloat: may grow fast…
So my question is : is there an “easy” and standard way of doing this ? Like an NSString formatter or something ? For example, replacing @"%.1f%%" with something like @"%sign%.1f%%" ?
If there’s nothing that straight, is something like stringFromFloat: the best solution ?
Thanks !
You do not need to make the sign part of the format – it can be parameterized, like this:
Even if you want to put it in the format, the format string can be prepared in an expression: